无法访问Django模型实例中的属性

时间:2018-11-14 05:28:30

标签: django-models

我有一个看起来像这样的模型:

class ClusterHosts(models.Model):
    host_name = models.TextField(max_length=300,  null=True)
    ... omitted for brevity ...
    cluster = models.ForeignKey(Cluster, null=True)

    @property
    def maintenance_mode(self):
        from vc.helpers import VcHelper
        vch = VcHelper()
        try:
            vc = self.cluster.data_center.virtual_center.name
            return vch.is_host_in_maint_mode(vc=vc, host=self.host_name)
        except:
            return 'Unknown'

然后我在python控制台中运行此查询:

>>> chs = ClusterHosts.objects.filter(create_date=datetime.datetime.today()
>>> for ch in chs:
...    print "%s %s" % (ch.host_name, ch.maintenance_mode)
...
Traceback (most recent call last):
  File "<input>", line 2, in <module>
AttributeError: 'ClusterHosts' object has no attribute 'maintenance_mode'

在另一个项目DRF教程中,我有以下模型:

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
    group = models.ForeignKey(GroupOfSnippets, null=True, on_delete=models.CASCADE)
    owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
    highlighted = models.TextField()

    @property
    def rand_number(self):
        return randint(1,100)

我可以做到这一点……

>>> ss = Snippet.objects.all()
>>> for s in ss:
...     print(s.rand_number)
...
92

那么为什么Snippet模型中可访问的属性无法工作,而ClusterHosts模型中的属性却无法访问?

0 个答案:

没有答案