How can I introspect properties and model fields in Django?

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

    The trouble is you say you only want fields, but then complicate things by throwing properties into the mix. There isn't really any easy way in Python of distinguishing between a property and any other random method. This isn't anything to do with Django: it's simply that a property is just a method that is accessed via a descriptor. Because any number of things in the class will also be descriptors, you'll have trouble distinguishing between them.

    Is there any reason why you can't define a list at the class level that contains all the properties you want, then just call getattr on each of the elements?

提交回复
热议问题