How can I introspect properties and model fields in Django?

后端 未结 4 1913
长发绾君心
长发绾君心 2021-01-05 02:55

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 an

4条回答
  •  长发绾君心
    2021-01-05 03:13

    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.

提交回复
热议问题