Django query to get User's favorite posts?

≯℡__Kan透↙ 提交于 2019-12-04 09:00:45

The thing to recognise is that your Favorite model is actually the through table of a many-to-many relationship between Post and User. Django can actually manage that automatically if you declare a ManyToManyField somewhere. Personally, I would do that on UserProfile - so the relationship actually becomes one between Post and UserProfile:

class UserProfile(models.Model):
    favorites = models.ManyToManyField(Post, related_name='favorited_by')

Now you don't need your get_favorites method, as it is available via userprofile.favorites.all(). You could just use this as-is in the template:

{% if post in userprofile.favorites.all %}Favorited!{% endif %}

but this will end up being extremely inefficient, as you'll be doing the same identical query for each post in your list of posts. So, use the {% with %} tag to get the favorites once before the loop:

{% with userprofile.favorites.all as favorite_posts %}
  {% for post in post_list %}
    {% if post in favorite_posts %}Favorited{% endif %}
    ...
  {% endfor %}
{% endwith %}

While Daniel makes good point, i'll just post the query you wanted :)

Post.objects.filter(favorite__user=user)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!