【发布时间】:2018-12-03 09:42:27
【问题描述】:
我遇到了这个错误:
File "/boo/foot/routing/models.py", line 133, in indexing
contact = self.contact.get_full_name() if self.contact else '',
AttributeError: 'NoneType' object has no attribute 'get_full_name'
我的代码是:
class Visit(models.Model):
contact = models.ForeignKey(Contact, on_delete=models.SET_NULL, null=True, blank=True )
def indexing(self):
obj = VisitIndex(
meta = { 'id' : self.id },
contact = self.contact.get_full_name() if self.contact else '',
)
print(obj)
obj.save()
并且索引方法附在post_save信号上:
@receiver(post_save, sender = Visit)
def index_post(sender, instance, **kwargs):
instance.indexing()
我正在测试self.contact 是否不虚假以获取get_full_name()... 然而,即使使用 NoneType 似乎也能到达那部分。问题可能出在哪里?
【问题讨论】:
-
任何其他
None;False;空容器(字符串、字典、列表);数字零;并且用户定义的 False 在 Python 中为 True。type(None)不是空的,也不是任何定义的 False 事物——因此是True。见Boolean Operations in Python -
输出
self.contact怎么样?第一次访问该对象时,它是一个ForeignKey表示 - 结果可能会有所不同。 @dawg - 如果它是一个类型对象,错误消息将是“.. type object 'NoneType' ...”。 -
@MatsLindh 我会尝试让他输出 self.contact