How to get the value of a Django Model Field object

前端 未结 3 1770
失恋的感觉
失恋的感觉 2021-01-31 09:28

I got a model field object using field_object = MyModel._meta.get_field(field_name). How can I get the value (content) of the field object?

3条回答
  •  无人共我
    2021-01-31 10:04

    Use value_from_object:

    field_name = 'name'
    obj = MyModel.objects.first()
    field_object = MyModel._meta.get_field(field_name)
    field_value = field_object.value_from_object(obj)
    

    Which is the same as getattr:

    field_name = 'name'
    obj = MyModel.objects.first()
    field_object = MyModel._meta.get_field(field_name)
    field_value = getattr(obj, field_object.attname)
    

    Or if you know the field name and just want to get value using field name, you do not need to retrieve field object firstly:

    field_name = 'name'
    obj = MyModel.objects.first()
    field_value = getattr(obj, field_name)
    

提交回复
热议问题