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

查看:20
本文介绍了如何内省 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)

我想要的是返回一个看起来像这样的字典:

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 来获取模型字段,但这并没有给我属性而不是真正的数据库字段.

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)

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

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天全站免登陆