Django模型继承和类型检查 [英] Django model inheritance and type check

查看:63
本文介绍了Django模型继承和类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Machine(models.Model):
    name= models.CharField( max_length=120)
    class Meta:
        abstract = True

class Car(Machine):
    speed = models.IntegerField()

class Computer(Machine)
    ram = models.IntegerField()

我的问题是,我如何理解机器模型的类型。对于instamce,我知道传入的查询是Machine模型的子级,但是我也想知道它是Car子模型。

My question is, how can I understand what type is the Machine model. For instamce I know the incoming query is a children of the Machine model but I also want to know it is a Car submodel.

推荐答案

我不确定我是否正确理解您的问题。 如果 ,您尝试查找给定实例的类型,则可以使用内置的 type 函数。

I am not sure if I understand your question correctly. If you are trying to find out the type of a given instance you can use the built-in type function.

an_object = Car(name = "foo", speed = 80)
an_object.save()
type(an_object) # <class 'project.app.models.Car'>

或者是否要检查 an_object Car 的实例,可以使用 isinstance

Or if you wish to check if an_object is an instance of Car you can use isinstance.

isinstance(an_object, Car) # True

这篇关于Django模型继承和类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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