如何在 Django 中编写连接两个表的查询?
How to write query for joining two tables in Django?
这里,我想要的是加入两个table,在Posttable中增加like value,在table中添加另一行UserLikes tables 与当前用户,PostId,has_liked = True
。还要检查当前用户是否已经喜欢当前的Post?下面是我的代码。
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 文件中的查询是什么?
Post
模型上的 likes
字段只是复制数据,而不是通过查询获取喜欢的数量,甚至可能使其成为 属性 of [=12] =] 如果你需要经常使用它
@property
def number_of_likes(self):
return self.userlikes_set.count()
剩下的就变得微不足道了,只需为此实例添加一个 userlike。
这里,我想要的是加入两个table,在Posttable中增加like value,在table中添加另一行UserLikes tables 与当前用户,PostId,has_liked = True
。还要检查当前用户是否已经喜欢当前的Post?下面是我的代码。
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 文件中的查询是什么?
Post
模型上的 likes
字段只是复制数据,而不是通过查询获取喜欢的数量,甚至可能使其成为 属性 of [=12] =] 如果你需要经常使用它
@property
def number_of_likes(self):
return self.userlikes_set.count()
剩下的就变得微不足道了,只需为此实例添加一个 userlike。