如何在Django中自省属性和模型字段? [英] How can I introspect properties and model fields in Django?

查看:66
本文介绍了如何在Django中自省属性和模型字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取给定对象的所有现有模型字段和属性的列表.有没有一种干净的方法可以对一个对象进行内省,以便我可以得到字段和属性的字典.

I am trying to get a list of all existing model fields and properties for a given object. Is there a clean way to instrospect an object so that I can get a dict of fields and properties.

class MyModel(Model)
    url = models.TextField()

    def _get_location(self):
        return "%s/jobs/%d"%(url, self.id)

    location = property(_get_location)

我想要的是一种返回如下所示的dict的东西:

What I want is something that returns a dict that looks like this:

{
  'id' : 1,
  'url':'http://foo',
  'location' : 'http://foo/jobs/1'
}   

我可以使用model._meta.fields来获取模型字段,但这并不能为我提供属性,而不能提供真正的DB字段.

I can use model._meta.fields to get the model fields, but this doesn't give me things that are properties but not real DB fields.

推荐答案

如果您只需要模型字段和属性(使用属性声明的字段),则:

If you strictly want just the model fields and properties (those declared using property) then:


def get_fields_and_properties(model, instance):
    field_names = [f.name for f in model._meta.fields]
    property_names = [name for name in dir(model) if isinstance(getattr(model, name), property)]
    return dict((name, getattr(instance, name)) for name in field_names + property_names)

instance = MyModel()
print get_fields_and_properties(MyModel, instance)

这里唯一额外的一点是通过 class 运行,以查找与属性描述符相对应的字段.通过类访问它们可以得到描述符,而通过实例可以得到值.

The only bit that's extra here is running through the class to find the fields that correspond to property descriptors. Accessing them via the class gives the descriptor, whereas via the instance it gives you the values.

这篇关于如何在Django中自省属性和模型字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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