Речь идет о менеджере, связанном с django

Django 5.1 Что означает q.choice_set.all() в приложении "Опросы"? 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,)))

Это описано в разделе Playing with the API в документации.

Чтобы лучше понять это, создайте свои классы моделей:

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)

Примените миграции, а затем вызовите оболочку Python, используя 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()

Из документации:

Предоставьте вопросу несколько вариантов выбора. Вызов create конструирует новый объект Choice, выполняет оператор INSERT, добавляет выбор в набор доступных вариантов и возвращает новый объект Choice. Django создает набор (определяемый как "choice_set") для хранения "другой стороны" отношения ForeignKey (например, выбора вопроса), к которому можно получить доступ через 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()

См. Играя с API.

Вернуться на верх