2016-01-24 36 views
0

models.py看起來是這樣的:如何使用Django模型以更高效的方式獲取此查詢集?

class Post(models.Model): 
    user = models.ForeignKey(User, related_name = 'user_posts') 
    title = models.CharField(max_length = 140) 
    votes = models.IntegerField(default = 0) 

class Vote(models.Model): 
    user = models.ForeignKey(User, related_name = 'user_votes') 
    post = models.ForeignKey(Post, related_name = 'post_votes') 
    is_voted = models.BooleanField(default = True) 
    class Meta: 
     unique_together = [('user', 'post')] 

讓我解釋一下我的投票制度是如何設置的。當用戶第一次投票時,會創建一個新的投票對象。如果用戶先投了票,用戶可以投票。在這種情況下,Vote對象中的is_voted屬性設置爲False。

現在在一個視圖中,我需要一個用戶已投票的帖子列表。這意味着存在帖子和用戶組合的Vote對象,並且該對象的is_voted屬性爲True。

這裏是我當前如何試圖做到這一點:

views.py

def user_profile(request, pk): 
    # Get user using pk 
    u = User.objects.get(pk = pk) 

    # Get a list of Votes using the user instance 
    votes = Vote.objects.filter(user = u, is_voted = True) 

    # Getting the list of posts using the votes list 
    post_list = Post.objects.none() # Generating empty list 
    for vote in votes: 
     # Adding vote.post to post_list using chaining. 
     ..... 

這實際工作,但感覺非常破解-Y。有沒有什麼辦法可以在沒有for循環的情況下生成查詢集?我猜我可以使用related_name,但我不知道如何去做。

回答

2

我覺得這個查詢集應該給用戶upvoted所有文章(我還沒有嘗試過,雖然):

votes = Post.objects.filter(post_votes__user=u, post_votes__is_voted=True) 

這是從模型反向查找到它指向的外鍵模型,包含它。

0

你可以試試這個:

post_list = [p.post for p in Vote.objects.filter(user = u, is_voted = True).select_related('post')]