我有:
class Foo(models.Model):
pass
class Bar(Foo):
pass
class Corn(Foo):
pass
# Now I have these objects in the database:
john = Corn()
mary = Corn()
joe = Bar()
grace = Corn()
randy = Bar()
在Django中,我使用它来获取Foo对象的列表:
foos = Foo.objects.all()
现在,我如何检查上面的foos列表中的对象是Bar还是Corn?
for x in foos:
print x.__class__.__name__ # returns Foo
答案 0 :(得分:0)
模型继承不会自动返回子类实例 - 如果你向ORM询问Foos,它会给你Foos。您需要询问是否存在具有相同主键的Bar对象:
for x in foos:
Bar.objects.filter(pk=x.pk).exists() # True if it's a Bar, too
Corn.objects.filter(pk=x.pk).exists() # True if it's a Corn, too
您也可以使用模型名称(小写)作为属性,它将为您进行查找,但不能保证成功(显然),因此您需要防范DoesNotExist异常:
for x in foos:
try:
x.bar
# it's a bar
except Bar.DoesNotExist:
# it's not a bar
pass
try:
x.corn
# it's a corn
except Corn.DoesNotExist:
# it's not a corn
pass