How can I introspect properties and model fields in Django?

后端 未结 4 1899
长发绾君心
长发绾君心 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:28

    You should use the dir() function on your instance. Skipping whatever starts with '__' and than use getattr to get the value from your instance.

    properties = [prop for prop in dir(SomeClass) if not prop.startswith("__")]
    
    obj = {}
    for prop in properties:
        obj[prop] = getattr(myinstance, prop)
    

提交回复
热议问题