我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,但我不知道如何去做。