如何在Django中编写连接两个表的查询?

时间:2016-11-24 09:03:13

标签: django django-models django-views python-3.5 django-orm

在这里,我想要的是加入两个表,在Post表中递增 like value ,在UserLikes表中添加另一行,其中包含当前用户,PostId,has_liked = True。还要检查当前用户是否已经喜欢当前的帖子?以下是我的代码。

models.py

class Posts(models.Model):
    title = models.CharField("Title", max_length=140)
    url = models.FileField("URL")
    likes = models.IntegerField("Likes", default=0)
    by = models.ForeignKey(User)
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title + ' by ' + str(self.by)

class UserLikes(models.Model):
    post = models.ForeignKey(Posts)
    user = models.ForeignKey(User)
    has_liked = models.BooleanField("Liked", default=False)

    def __str__(self):
        return str(self.post) + ' by ' + str(self.user)

views.py

def like(request, pk):
    if request.POST :
        post = get_object_or_404(Posts, pk=pk)
        print(request.user)
        obj = UserLikes.objects.filter(post_id__in=post.id, user=request.user)
        try:
            if obj.has_liked is not True:
                obj.post_id = post.id
                obj.user = request.user
                obj.has_liked = True
                obj.save()

            post.likes = str(int(post.likes) + 1)
            post.save()
        except AttributeError:
            return HttpResponse(post.likes)
    else:
        return HttpResponse(post.likes, {'like': 'disabled'})

urls.py

url(r'^(?P<pk>\d+)/like/$', views.like, name='likes'),

那么,views.py文件中的查询是什么?

1 个答案:

答案 0 :(得分:0)

likes模型上的Post字段只是复制数据,而只是通过查询得到喜欢的数量,如果需要,甚至可以使其成为Post的属性使用它很多

@property
def number_of_likes(self):
    return self.userlikes_set.count()

其余部分变得微不足道,只需为此实例添加用户名。