django公式チュートリアル2
でmodelにデータを追加するためにAPI?を操作していたのですが、
いきなりq.choice_set.all()で定義されていないchoice_setを使用しており、Questionオブジェクトにはchoice_setフィールドがないのでなぜこのようなことができるのかわかりません。試しにchoice_testとして同様にできるのか試しましたが、できませんでした。なぜこのようなことができるのか教えてください。
models.py
1import datetime 2 3from django.db import models 4from django.utils import timezone 5 6# Create your models here. 7class Question(models.Model): 8 question_text = models.CharField(max_length=200) 9 pub_date = models.DateTimeField('date published2') 10 def __str__(self): 11 return self.question_text 12 13 def was_published_recently(self): 14 return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 15 16class Choice(models.Model): 17 question = models.ForeignKey(Question, on_delete=models.CASCADE) 18 choice_text = models.CharField(max_length=200) 19 votes = models.IntegerField(default=0) 20 def __str__(self): 21 return self.choice_text
python manage.py shellでAPI?を起動したときの操作↓
# 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 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?>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/19 12:17 編集