【问题标题】:AttributeError: '***' object has no attribute '***_set'AttributeError:“***”对象没有属性“***_set”
【发布时间】:2019-12-22 16:18:37
【问题描述】:

如果有人可以帮助我,我会很高兴。

我想要做的:在作者被删除后将所有“投票”更改为零。

class Author(models.Model):
    """Model representing an author."""

    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField('died', null=True, blank=True)

    class Meta:
        ordering = ['last_name', 'first_name']

    def get_absolute_url(self):
        """Returns the url to access a particular author instance."""
        return reverse('catalog:author-detail', args=[str(self.id)])

    def __str__(self):
        """String for representing the Model object."""
        return '{0}, {1}'.format(self.last_name, self.first_name)


class Option(models.Model):
    def default_votes():
        d=Author.objects.all().first()
        print(dir(d))
        for a in d.option_set.all():
            a.votes=0
    author = models.ForeignKey(Author, on_delete=models.SET_DEFAULT, default=default_votes())
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

但我明白了:

  File "C:\Users\chainsaw\Desktop\django-locallibrary-tutorial-master\django-loc
allibrary-tutorial-master\catalog\models.py", line 128, in default_votes
    for a in d.option_set.all():
AttributeError: 'Author' object has no attribute 'option_set'

但是在shell中有这个属性。我可以改变它。我做错了什么?

【问题讨论】:

  • 还包括您收到此错误的代码。
  • 尝试删除default=default_votes() 中的() 看看是否适合您?

标签: python django shell django-queryset


【解决方案1】:

小问题是你实际上不应该调用你的默认函数;只需删除():

author = models.ForeignKey(Author, on_delete=models.SET_DEFAULT, default=default_votes)

【讨论】:

    【解决方案2】:

    您已将 default 值设置为 default=default_votes() 因为 不是“可调用函数”,Django 在创建迁移文件时获取函数的结果

    因此,将默认参数设置为可调用函数(仅提供函数,不提供括号)

    author = models.ForeignKey(Author, on_delete=models.SET_DEFAULT, <b>default=default_votes</b>)

    注意:你的函数default_votes没有返回任何东西,所以,从函数中返回“适当的值” .

    【讨论】:

      猜你喜欢
      • 2012-11-30
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2021-04-19
      • 2021-11-22
      相关资源
      最近更新 更多