Search code examples
djangodjango-modelsmany-to-manydjango-querysetm2m

Django 1.8: When items are related via two separate relationships, how can I specify which relationship to use?


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?


Solution

  • 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`