pythondjangoorm

it is about django related manager


Django 5.1 What is the meaning of question.choice_set.get() in the polls app? https://docs.djangoproject.com/en/5.1/intro/tutorial04/

from django.db.models import F
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, Question


def vote(request, question_id):
     question = get_object_or_404(Question, pk=question_id)
try:
    selected_choice = question.choice_set.get(pk=request.POST["choice"])
except (KeyError, Choice.DoesNotExist):
    # Redisplay the question voting form.
    return render(
        request,
        "polls/detail.html",
        {
            "question": question,
            "error_message": "You didn't select a choice.",
        },
    )
else:
    selected_choice.votes = F("votes") + 1
    selected_choice.save()
    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button.
    return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))

Solution

  • This is described in the Playing with the API section of the docs.

    To better understand this, create your model classes:

    from django.db import models
    
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField("date published")
    
    
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
    

    Apply your migrations and then invoke the Python shell using python manage.py shell

    >>> from polls.models import Choice, Question  # Import the model classes we just wrote.
    >>> from django.utils import timezone
    
    # Create a new Question.
    >>> q = Question(question_text="What's new?", pub_date=timezone.now()) 
    
    # Save the object into the database. You have to call save() explicitly.
    
    >>> q.save()
    

    From the docs:

    Give the Question a couple of Choices. The create call constructs a new Choice object, does the INSERT statement, adds the choice to the set of available choices and returns the new Choice object. Django creates a set (defined as "choice_set") to hold the "other side" of a ForeignKey relation (e.g. a question's choice) which can be accessed via the API.

    >>> q = Question.objects.get(pk=1)
    
    # Display any choices from the related object set -- none so far.
    >>> q.choice_set.all()
    <QuerySet []>
    # Create three choices.
    >>> q.choice_set.create(choice_text="Not much", votes=0)
    <Choice: Not much>
    >>> q.choice_set.create(choice_text="The sky", votes=0)
    <Choice: The sky>
    >>> c = q.choice_set.create(choice_text="Just hacking again", votes=0)
    
    # Choice objects have API access to their related Question objects.
    >>> c.question
    <Question: What's up?>
    
    # And vice versa: Question objects get access to Choice objects.
    >>> q.choice_set.all()
    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
    >>> q.choice_set.count()
    3
    
    # The API automatically follows relationships as far as you need.
    # Use double underscores to separate relationships.
    # This works as many levels deep as you want; there's no limit.
    # Find all Choices for any question whose pub_date is in this year
    # (reusing the 'current_year' variable we created above).
    >>> Choice.objects.filter(question__pub_date__year=current_year)
    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
    
    # Let's delete one of the choices. Use delete() for that.
    >>> c = q.choice_set.filter(choice_text__startswith="Just hacking")
    >>> c.delete()
    

    See Playing with the API.