Django 1.8: When elements are related through two separate relationships, how can I tell which relationship to use?

I have User

(django default model) and Interest

.

They are related to each other through two many-to-many models, so keep track of additional relationship data.

One model Selected

,, tracks of interest to the user, must be linked to.

Another model Recommended

lists the interests offered to the user.

Give an object User

, how can I get to one of them? user.interest_set.all()

returns percent using only Selected

. How can I specify which relationship / via model to use?

+3


source to share


1 answer


Django doesn't even let you define two relationships between the same models unless you define related_name

. Thus, you are using this 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`

      

+2


source







All Articles