在基类之后确定查询后的Django模型实例类型 [英] Determining Django Model Instance Types after a Query on a Base-class

查看:193
本文介绍了在基类之后确定查询后的Django模型实例类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法确定Django数据库对象的真实类在从基类的查询中返回之后?

Is there a way to determine what the 'real' class of a Django database object is, after it has been returned from a query for on a base class?

例如,如果我有这些模型...

For instance, if I have these models...

class Animal(models.Model):
    name= models.CharField(max_length=128)

class Person(Animal):
    pants_size = models.IntegerField(null=True)

class Dog(Animal):
    panting_rate = models.IntegerField(null=True)

并创建这些实例...

And create these instances...

Person(name='Dave').save()
Dog(name='Mr. Rufflesworth').save()

如果我像 Animal.objects.all (),我最终得到两个 Animal 实例,而不是 Person 的实例,一个 Dog 的实例。有没有办法确定哪个实例是哪个类型?

If I do a query like Animal.objects.all(), I end up with two Animal instances, not an instance of Person and an instance of Dog. Is there any way to determine which instance is of which type?

FYI:我已经尝试这样做了...

FYI: I already tried doing this...

isinstance(Animal.objects.get(name='Dave'),Person) # <-- Returns false!

但似乎不起作用。

推荐答案

我过去有类似的问题,最终找到一个满意的解决方案,谢谢这个答案

I had a similar problem in the past and eventually found a satisfactory solution thanks to this answer.

通过实现存储真实类的抽象类,并让它由父类继承,一旦可以将每个父类实例转换为实际类型。 (该答案中使用的抽象类现在可以在 django-model-utils 。)

By implementing an abstract class that stores the real class and have it inherited by your parent class, once can cast each parent class instance to the actual type. (The abstract class used in that answer is now available in django-model-utils.)

例如,一旦你定义了抽象类(或者你有django-model-utils),你可以简单地做:

For example, once you have the abstract class defined (or if you have django-model-utils), you can simply do:

class Animal(InheritanceCastModel):
    name= models.CharField(max_length=128)

class Person(Animal):
    pants_size = models.IntegerField(null=True)

class Dog(Animal):
    panting_rate = models.IntegerField(null=True)

使用它是微不足道的:

>>> from zoo.models import Animal, Person, Dog
>>> Animal(name='Malcolm').save()
>>> Person(name='Dave').save()
>>> Dog(name='Mr. Rufflesworth').save()
>>> for obj in Animal.objects.all():
...     print obj.name, type(obj.cast())
...
Malcolm <class 'zoo.models.Animal'>
Dave <class 'zoo.models.Person'>
Mr. Rufflesworth <class 'zoo.models.Dog'>

这篇关于在基类之后确定查询后的Django模型实例类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆