3 table many to many relationship

107 views
Skip to first unread message

Malik Rumi

unread,
Apr 23, 2014, 11:24:04 PM4/23/14
to django...@googlegroups.com

I was designing the models I will need for this project. I designed an intermediate table for two models, A and B, and then started to sketch out an intermediate table for two other models, A and C, when I realized that these two intermediate tables both use A, and further, the information in the second intermediate table will be a lot more valuable it if also shows the relationship C has to B.

I looked at the Many to Many documentation on the official Django site, but I don’t see a discussion of this three table option. I have seen it elsewhere, so I assume it can be done. What I don’t assume is the impact this has on performance and other issues I might not even anticipate. So, my questions:

   Can this three sided many to many intermediate table be created in Django?

    If it can, is it advisable, or are there better / more efficient ways of doing this, like with two intermediate tables as I was originally thinking?

thx.

Simon Charette

unread,
Apr 23, 2014, 11:43:17 PM4/23/14
to django...@googlegroups.com
Django allows you to explicitly specify an intermediary model for many-to-many relationships with the `through` option.

class A(models.Model):
    b_set = models.ManyToMany('B', related_name='a_set', through='R')
    c_set = models.ManyToMany('C', related_name='a_set', through='R')

class B(models.Model):
    pass

class C(models.Model):
    pass

class R(models.Model):
    a = models.ForeignKey('A')
    b = models.ForeignKey('B')
    c = models.ForeignKey('C')

However you'll loose the ability of directly adding objects to relationships (A().b_set.create() won't work).
You'll need to explicitly create `R` instances instead: R.objects.create(a=a, b=b, c=c).

Simon

Malik Rumi

unread,
Apr 26, 2014, 8:54:45 PM4/26/14
to django...@googlegroups.com
Merci beaucoup


--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/Z53HNI9t8Rw/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@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/2e128d84-3e70-4bab-8b70-696eaaa369c1%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages