Django比较列表和过滤对象

时间:2013-08-17 02:43:10

标签: django list filter many-to-many views

我们希望向用户显示我们网站上的所有图片。在另一页面中,我们向用户显示他/她喜欢的照片。

在查看功能后,用户无法在displayallpics.html中查看他们已经喜欢过的照片。

我们希望过滤掉用户喜欢的所有照片,并在displayallpics.html中仅显示用户不喜欢的照片:

这是我们想要做的sql:

select * from alphart_picdetails where id not in (select picture_id from alphart_like where user_id = 4);

user_id =登录的用户 - 我们无法让django这样做。

感谢您的帮助。

models.py


class PicDetails(models.Model): 
    poster = models.ForeignKey(User)
    Title = models.CharField(max_length=50)
    date = models.DateField(("Date"), auto_now_add=True)

    def __unicode__(self):
        return self.Title

class Like(models.Model):
   user = models.ForeignKey(User)
   picture = models.ForeignKey(PicDetails)
   created = models.DateTimeField(auto_now_add=True)
   votes = models.IntegerField()

views.py

def findpics(request): #designed to return all pics posted on the site -the pics user has liked
  like_list = Like.objects.filter(user=request.user)
  user = request.user
  user_list = PicDetails.objects.filter(like=69)

  return render_to_response("displayallpics.html", {'user_list':user_list,   'like_list':like_list, 'user':user})

模板displayallpics.html:

    {% for object in user_list %}
    {{ object.Title }} 
    {% endfor %}    

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

non_liked_pics = PicDetails.objects.exclude(like__user=request.user)
liked_pics = PicDetails.objects.filter(like__user=request.user)

并在模板中

{% for pic in non_liked_pics %}
    {{ pic.picture.Title }} 
{% endfor %} 

{% for pic in liked_pics %}
    {{ pic.picture.Title }} 
{% endfor %} 

文档here

只需确保在上下文中发送变量