Django教程中的choice_set

4

来自Django教程:

我把我的模型定义如下:

from django.db import models
import datetime
from django.utils import timezone

# Create your models here.

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):  # Python 3: def __str__(self):
        return self.question
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __unicode__(self):  # Python 3: def __str__(self):
        return self.choice_text

选择集在哪里定义了?它是如何工作的?
>>> p = Poll.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
2个回答

4

这个 Python 功能叫什么,它可以动态生成方法? - DD.
这被称为元类编程,你可以在这里阅读相关内容:http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html - 在 Django 中,当你从 models.Model 继承时就会执行它。 - Henrik Andersson

0

choice_set 在任何地方都没有定义。

Django 为关系定义模型到相关模型的“另一侧”创建了 API 访问器。例如,一个投票对象 p 可以通过 choice_set 属性访问所有相关选项对象的列表:p.choice_set.all()。

所以 choice_set。其中 choice 是您的小写 Choice 模型,_set 是 Django 管理工具的一种。

详细信息可以在 right here 阅读。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接