django object get/set field

前端 未结 4 626
孤城傲影
孤城傲影 2020-12-08 00:52

Can I get the value of an object field some other way than obj.field? Does something like obj.get(\'field\') exist? Same thing for setting the valu

相关标签:
4条回答
  • 2020-12-08 01:20

    If somebody stumbles upon this little question, the answer is right here: How to introspect django model fields?

    0 讨论(0)
  • 2020-12-08 01:32

    To get related fields:

    def getattr_related(obj, fields):
        a = getattr(obj, fields.pop(0))
        if not len(fields): return a
        else:               return getattr_related(a, fields)
    

    E.g.,

    getattr_related(a, "some__field".split("__"))
    

    Dunno, perhaps there's a better way to do it but that worked for me.

    0 讨论(0)
  • 2020-12-08 01:37

    why do you want this?

    You could use

    obj.__dict__['field']
    

    i guess... though it's not a method call

    changed=[field for (field,value) in newObj.__dict__ if oldObj.__dict__[field] != value]
    

    will give you a list of all the fields that where changed.

    (though I'm not 100% sure)

    0 讨论(0)
  • 2020-12-08 01:40

    To get the value of a field:

    getattr(obj, 'field_name')
    

    To set the value of a field:

    setattr(obj, 'field_name', 'field value')
    

    To get all the fields and values for a Django object:

    [(field.name, getattr(obj,field.name)) for field in obj._meta.fields]
    

    You can read the documentation of Model _meta API which is really useful.

    0 讨论(0)
提交回复
热议问题