Wednesday, September 2, 2015

Re: Basic M2M Self Reference Through Question


On Sep 2, 2015 9:51 AM, "jeff newburn" <jeffnb@gmail.com> wrote:
>
> I apologize if this is basic and I am just missing something in the django docs.  The Django ORM allows you to do a self reference through another table.  I understand everything about this process EXCEPT how Django determines which of the foreign keys to use for each side of the M2M relationship.
>
> class MyUser(...):
>     connections = models.ManyToManyField('self', through=Relationship, symmetrical=False)
>
> class Relationship(...):
>     follower = models.ForeignKey(MyUser)
>     following = models.ForeignKey(MyUser)
>
> So in the psuedocode example above how does Django ORM know which of the 2 foreign key fields to connect to?  Does it just assume the first field is the one to use?  Thanks for any help on this.
>

When you have multiple references to the same model, you have to do a bit of extra work to tell Django how you want things to line up. I think what you need to do is specify the 'through_fields' on the M2M, and set appropriate 'related_name' arguments for the FK's.

https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ManyToManyField.through_fields

-James

--
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/CA%2Be%2BciWUHERQxWxOzraYknnZSdpPU654vu4DRVQasG8Fqf9Hfg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment