Django filter objects foreign key from another table

Viewed 903

Two tables: post and rating.

rating contains column - post (FK) that is post table's primary ID. I'm trying to filter table rating by columns user and ratingtype to get post (FK) value that I could use to filter post table by.

Post.objects.filter(pk__in=Rating.objects.get(post=post).filter(Rating.objects.filter(user = self.request.user, ratingtype='like')))
1 Answers

You can look "through" relations with two consecutive underscores (__), so:

Post.objects.filter(
    rating__user=self.request.user,
    rating__ratingtype='like'
).distinct()

The .distinct() [Django-doc] clause prevents returing the same Post multiple times if the user has given multiple ratings.

If you specified a related_query_name=… [Django-doc] or related_name=… [Django-doc] in the ForeignKey, then that is the name of the relation in reverse, so then instead of rating__ it is related_query_name__ (with related_query_name the value you used for the related_query_name=… parameter).

Related