How to get the value of a Django Model Field object

半城伤御伤魂 提交于 2020-12-27 08:19:08

问题


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?


回答1:


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)



回答2:


Assuming you have a model as,

class SampleModel(models.Model):
    name = models.CharField(max_length=120)

Then you will get the value of name field of model instance by,

sample_instance = SampleModel.objects.get(id=1)
value_of_name = sample_instance.name



回答3:


If you want to access it somewhere outside the model You can get it after making an object the Model. Using like this

OUSIDE THE MODEL CLAA:

myModal = MyModel.objects.all()

print(myModel.field_object)

USING INSIDE MODEL CLASS
If you're using it inside class you can simply get it like this

print(self.field_object)


来源:https://stackoverflow.com/questions/51905712/how-to-get-the-value-of-a-django-model-field-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!