繁体   English   中英

Django的通用视图:如何根据外部类属性过滤get_queryset?

[英]Django's Generic Views: how to filter get_queryset based on foreign class attributes?

我一直在关注Django入门教程( https://docs.djangoproject.com/en/1.8/intro/tutorial05/

到目前为止,我决定进行一些修改以测试我的技能。

具体来说,我打算为ResultsView通用视图实现自定义get_queryset

像这样:

# views.py
class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

    def get_queryset(self):
        '''
        Make sure we are displaying results for choices which have 1+ votes
        '''
        return Question.objects.get ...

基本上,我的目标是仅对至少1票的选票返回问题的选票

因此,我在Django的shell中尝试了以下操作:

# Django shell
q = Question.objects.get(pk=1)
q.choice_set.filter(votes=1)
[<Choice: Not much>]

在这里,我得到pk = 1的问题,然后基于choice_set(Choice模型的fk代表Question模型)进行过滤。

我试图弄清楚如何在我的views.py中实现它,以便它仅对票数超过1的选项(即显示所有具有相关票数的选项,但显示票数为0的选项)返回问题的内容(即选项)。

为了完整起见,这里是实际的模板(polls / results.html):

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {# pluralize used to automatically add "s" for values with 0 or 2+ choice.votes #}
{% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

楷模

# models.py
Class Question(models.Model): 

    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):             
        return self.question_text

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self): 
        return self.choice_text

我认为__关系应该对您有利。

像这样的东西?

def get_queryset(self):

    return Question.objects.filter(choices__votes__gte=1)

编辑:

您实际上想重载get_object。 在此处查看get()和get_object的定义: https ://ccbv.co.uk/projects/Django/1.8/django.views.generic.detail/Det​​ailView/

具体来说,类似于:

pk = self.kwargs.get(self.pk_url_kwarg, None)
Choice.objects.filter(question__pk=pk, votes__gte=1)

您正在执行的操作有点奇怪,因为详细视图通常可以在一个对象上使用,但这应该可以使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM