我的django应用程序中有以下模型:
from django.contrib.auth.models import User
class Poll(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User)
class Choice(models.Model):
poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
text = models.CharField(max_length=200)
class Vote(models.Model):
choice = models.ForeignKey(Choice)
user = models.ForeignKey(User)
对于给定的投票,我需要在模板中显示一个双条目表,如下所示,列出在该投票中投票的所有用户,并为用户投票的每个选项放置一个“x”:
[choice1] [choice2] [choice3]
[user1] x
[user2] x x
[user3] x
[user4] x x
我知道的问题是:
# get all votes for the given Poll (pk)
votes = Vote.objects.filter(choice__poll__pk=pk)
# get all users that has voted
usernames = votes.values('user__username')
# get the choices for the Poll
choices = Poll.objects.get(pk=pk).choice_set.all()
我通过以下方法解决了问题:
例如,在PostgreSQL中,在这种sql查询中转换的qs用户:
视图和模板可以如下所示(您甚至不需要将上下文传递给模板,所有内容都将取自Poll模型属性):
我不得不添加自定义模板过滤器来获得attr by choice id(很可能我错过了更优雅的解决方案):
相关问题 更多 >
编程相关推荐