3

I have User (django's default model) and Interest.

They are related to eachother through two many-to-many through models, so track additional data on the relationships.

One model, Selected, tracks which interests a user wants to be associated with.

The other model, Recommended, lists interests to suggest to the user.

Give a User object, how can I get to either one? user.interest_set.all() returns interests via Selected only. How can I specify which relation/through model to use?

StringsOnFire
  • 2,726
  • 5
  • 28
  • 50

1 Answers1

2

Django doesn't even allow you to define two relationships between the same models unless you define related_name. So you use that attribute.

class Interest(models.Model):
    user_selected = models.ManyToManyField(
         User, through="Selected", related_name="selected_interests")
    user_recommended = models.ManyToManyField(
         User, through="Recommended", related_name="recommended_interests")


my_user.selected_interests.all()  # Interests where the user is in `user_selected`
my_user.recommended_interests.all()  # Interests where the user is in `user_recommended`
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • That looks right, but the `user_recommended` line gives me this error: File "C:\Python34\lib\site-packages\django\db\models\base.py", line 1624, in _check_long_column_names for m2m in f.rel.through._meta.local_fields: AttributeError: 'str' object has no attribute '_meta' – StringsOnFire Jul 31 '15 at 12:15
  • I think this could be because the `through` model is in a separate app that creates recommendations, so I need to reference it differently in the `through` attribute? – StringsOnFire Jul 31 '15 at 12:21
  • I've asked it in a separate question: http://stackoverflow.com/questions/31746235/ – StringsOnFire Jul 31 '15 at 12:28