'Django query to get User's favorite posts?
I'm a little confused by the Django lingo. So I have 3 models: Post, UserProfile(User), Favorite. Favorite keeps track of which Posts a User has favorited.
Post--->Favorite<---User/UserProfile
Favorite model:
class Favorite(models.Model):
user = models.ForeignKey(User, unique=False)
post = models.ForeignKey(Post, unique=False)
def __unicode__(self):
return self.user.username
UserProfile model:
class UserProfile(models.Model) :
user = models.ForeignKey(User, unique=True)
def get_favorites(self):
if self.user:
return self.user.favorite_set.all()
In my post_list view I pass all Posts to my template, and in the template I have a for loop that displays all Posts.
{% for post in post_list %}
<hr/>
<div id=”post_{{ post.id }}”>
{% include 'posts/_post.html' %}
</div>
{% endfor %}
Now in that for loop I would like to put a logic that will display "Favorited!" if the logged-in User has favorited the Post. I think the conventional SQL is something like this:
SELECT favorite.post FROM favorite WHERE favorite.user = user.id
So that in the template loop I can do
{% if post in the.above.SQL.query%}Favorited!{% endif %}
Now I just can't translate that to Django lingo for some reason. Your help is much appreciated!
Solution 1:[1]
While Daniel makes good point, i'll just post the query you wanted :)
Post.objects.filter(favorite__user=user)
Solution 2:[2]
Since its many to many relationships,
fav_post = user.favourite.all() you can pass this fav_post to context. Then in the template, you will need to iterate that context key
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dmitry Shevchenko |
| Solution 2 | Hardik Patil |
