如何为给定用户添加对象的喜欢

时间:2013-08-17 18:12:45

标签: django django-views django-orm

我有一个论坛模型。在那里,我有一个问题,身体,pub_date,图像,创作者,喜欢的领域。从管理员,我可以为特定论坛的特定用户添加喜欢。但我现在很困惑,如何在视图中为request.user添加喜欢的内容?

models.py:

class Forum(models.Model):
    question = models.CharField(max_length=150)
    body = models.TextField()
    pub_date = models.DateTimeField(default=datetime.now)
    image = models.ImageField(upload_to=get_upload_file_name)
    creator = models.ForeignKey(User, related_name="creator_set")
    likes = models.ManyToManyField(User, through="Like")

    def __unicode__(self):
        return self.question

class Like(models.Model):
    forum = models.ForeignKey(Forum)
    liked = models.ForeignKey(User)
    liked_date = models.DateTimeField(default=datetime.now)

    def __unicode__(self):
        return "%s likes %s" % (self.liked, self.forum)

我想这样做:

>>>forum = Forum.objects.get(id=1)
>>>user = request.user
>>>user.like_set.add(forum)

但是,它没有帮助。请,任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

首先,您需要create a URL定位视图。该网址会传递forum_id作为网址参数。

from datetime import datetime
from django.shortcuts import get_object_or_404

@login_required
def update_likes(request, forum_id):
    forum = get_object_or_404(Forum, id=forum_id)
    like, _ = Like.objects.get_or_create(user=request.user, forum=forum, 
                   defaults={'liked_date': datetime.now()})
    #rest of the code here. 

这是一种方式。您也可以按照您想要的方式执行此操作,但您必须手动控制可能生成的重复项。 (您可以在('forum', 'liked')

上指定unique_together

并删除

@login_required
def delete_likes(request, forum_id):
    forum = get_object_or_404(Forum, id=forum_id)
    like = get_object_or_404(Like, user=request.user, forum=forum)
    like.delete()
    #rest of the code here.