【问题标题】:Django official tutorial models part4Django 官方教程模型 part4
【发布时间】:2018-11-29 07:15:17
【问题描述】:

我在第 4 部分关注 djangoproject 官方教程,它使用 question.choice_set Statment 我不知道 choice_set 是什么意思有人可以帮助我吗?

我可以使用 question.Objects 代替 question.choice_set 吗?

【问题讨论】:

    标签: python django forms web model


    【解决方案1】:

    modelname_set 是默认属性名称,您可以通过它访问反向相关对象。因此,在您的模型中,您的模型如下:

    class Question(Model):
        ...
    
    class Choice(Model):
        question = ForeignKey(Question)
        ...
    

    因此,如果您想获得与特定问题相关的所有选项,您可以使用以下语法:

    question.choice_set.all()
    

    您可以使用related_name 参数将属性名称更改为更易于阅读的名称:

    class Choice(Model):
        question = ForeignKey(Question, related_name='choices')
    

    在这种情况下,您现在可以使用question.choices.all() 来获取问题的选择。

    【讨论】:

      【解决方案2】:

      如果您将ForeignKeyChoice 变为Question,例如:

      class Choice(models.Model):
          # ...
          question = models.ForeignKey(Question, on_delete=models.CASCADE)

      然后 Django 自动创建一个相反的关系。默认情况下,关系的名称是nameofmodel_set

      由于可以有多个 Choice 对象映射到相同 Question,因此这是一个集合(可以包含零个、一个或多个对象的集合)。

      因此,通过使用somequestion.choice_set,您将获得一个ObjectManager,它处理特定 Question 实例(此处为somequestion)的所有Choice 对象。

      然后,您可以在该集合上使用 .filter(..),或 .update(..) 或编写自定义 ORM 查询。例如somequestion.choice_set.all() 会给你all相关的Choices。

      有时这个反向关系的名字不是很好,这种情况下,你可以使用reated_name参数,给它另一个名字,比如:

      class Choice(models.Model):
          # ...
          question = models.ForeignKey(Question,
                                       on_delete=models.CASCADE,
                                       related_name='options')

      如果您不想要这种反向关系(例如因为它会导致很多混乱),那么您可以使用'+' 作为related_name

      class Choice(models.Model):
          # ...
          # no opposite relation
          question = models.ForeignKey(Question,
                                       on_delete=models.CASCADE,
                                       related_name='+')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-07
        • 1970-01-01
        • 2013-03-11
        • 2018-11-13
        • 1970-01-01
        • 2014-12-11
        • 2014-11-15
        • 1970-01-01
        相关资源
        最近更新 更多