Thursday, July 30, 2015

Two-to-Many Mapping between Models in Django ORM

Dear All,

I'm new to the Django ORM, and quite new to ORMs in general.  I have two models (lets call them A and B) between which I have an interesting mapping.  There are precisely 2 B instances associated with each A instance.  Each A instance can have many B instances.  The order of Bs are important for As.

I want to do something like this:

class A(models.Model):
  b_1 = models.ForeignKey(B)
  b_2 = models.ForeignKey(B)

class B(models.Model):
  pass

Such that i can do:

>>> b1, b2, b3 = B(), B(), B()
>>> a1, a2 = A(b_1=b1, b_2=b2), A(b_1=b2, b_2=b3)
>>> b2.as
[<A ... >, <A ... >] #(order doesn't matter)

I expect I could eventually do something a bit hacky that would work, but what would be the best way to handle this?

Thanks in advance,

Richard

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3250c3c4-7598-4104-8a7b-1a0aa313a253%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment