我有以下模型:
class A(models.Model):
name = models.CharField(max_length=50)
content_type = models.ForeignKey(ContentType)
这个模型应该是一些继承树中的根模型,而 content_type 属性是一种关于真正存储什么类型的提示。
显然,我应该计算
content_type
在 A 实例创建时透明。我认为,在 __init__
.但是有一个问题——创建 A 实例有两个主要上下文:a = A(name='asdfdf') # here we must fill in content_type
QuerySet
机械用*args
元组。在这种情况下,我不应该填写 content_type
所以,我试图写:
def __init__(self, *args, **kwargs):
super(A, self).__init__(*args, **kwargs)
if self.content_type is None: # << here is the problem
self.content_type = ContentType.objects.get_for_model(self)
事情是
self.content_type
是 ReverseSingleRelatedObjectDescriptor
实例与 __get__
覆盖,以便在未设置值的情况下抛出。是的,我可以执行以下操作:def __init__(self, *args, **kwargs):
super(A, self).__init__(*args, **kwargs)
try:
self.content_type
except Exception, v:
self.content_type = ContentType.objects.get_for_model(self)
但我不喜欢。是否有更“礼貌”的方式来检查
ForeignKey
属性设置?
最佳答案
如果您检查 self.content_type_id
是否有效?而不是 self.content_type
?
关于Django:检查是否设置了外键属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2005161/