python - Django's Generic Views: how to filter get_queryset based on foreign class attributes? -


i've been following django starter tutorial ( https://docs.djangoproject.com/en/1.8/intro/tutorial05/ )

i decided make modifications test skills of now.

specifically intend implement custom get_queryset resultsview generic view.

something this:

# views.py class resultsview(generic.detailview):     model = question     template_name = 'polls/results.html'      def get_queryset(self):         '''         make sure displaying results choices have 1+ votes         '''         return question.objects.get ... 

basically goal return questions' choices choices at least 1 vote.

so tried in django's shell this:

# django shell q = question.objects.get(pk=1) q.choice_set.filter(votes=1) [<choice: not much>] 

here question pk = 1, filter based on choice_set (of choice model, fk refers question model).

i'm trying figure out how implement in views.py, returns questions' content (i.e. choices) choices 1+ votes (i.e. displaying choices related votes choices 0 votes).

just completeness here actual template (polls/results.html):

<h1>{{ question.question_text }}</h1>  <ul> {% choice in question.choice_set.all %}     <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {# pluralize used automatically add "s" values 0 or 2+ choice.votes #} {% endfor %} </ul>  <a href="{% url 'polls:detail' question.id %}">vote again?</a> 

models

# 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):         = timezone.now()         return - datetime.timedelta(days=1) <= self.pub_date <=  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 

i think __ relations should you.

something maybe?

def get_queryset(self):      return question.objects.filter(choices__votes__gte=1) 

edit:

you want overload get_object. see definitions of get() , get_object here: https://ccbv.co.uk/projects/django/1.8/django.views.generic.detail/detailview/

specifically, like:

pk = self.kwargs.get(self.pk_url_kwarg, none) choice.objects.filter(question__pk=pk, votes__gte=1) 

what doing little weird because detail view works on 1 object, should work.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -