2016-11-24 86 views
0

在這裏,我想要加入兩個表,在Post表中增加類似值,在UserLikes表中添加另一行,使用當前User,PostId,has_liked = True。還要檢查當前用戶是否已經喜歡當前的Post?以下是我的代碼。如何編寫在Django中連接兩個表的查詢?

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文件?

回答

0

Post模型likes場只是複製數據,而不是隻得到喜歡的數量與查詢,甚至使它的Post的屬性,如果你需要經常使用它

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

剩下的就變得微不足道了,只需添加一個像這樣的用戶。

+0

謝謝@Sayse,但我不明白的是如何限制每個用戶只喜歡一次,並將其存儲在UserLikes表中。還有如何檢索它,也就是說,當索引頁打開時,查詢會是什麼? – CapJ

+0

@CapJ如果您只希望每個用戶都喜歡每個帖子,只需在UserLikes模型中設置unique_together =('post','user')':https://docs.djangoproject.com/en/1.10/ref/models/options /#unique-together –

+0

謝謝@elkubo確實幫了我。 – CapJ

相關問題