简体   繁体   English

如何获取 Django 模型字段对象的值

[英]How to get the value of a Django Model Field object

I got a model field object using field_object = MyModel._meta.get_field(field_name) .我使用field_object = MyModel._meta.get_field(field_name)获得了模型字段对象。 How can I get the value (content) of the field object?如何获取字段对象的值(内容)?

Use value_from_object :使用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 :这与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)

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,然后您将通过以下方式获取模型实例的name字段的值,

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

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 : OUSIDE 模型 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)

Here is another solution to return the nth field of a model where all you know is the Model's name.这是返回模型的第 n 个字段的另一种解决方案,您只知道模型的名称。 In the below solution the [1] field is the field after pk/id.在以下解决方案中,[1] 字段是 pk/id 之后的字段。

model_obj = Model.objects.get(pk=pk)
field_name = model_obj._meta.fields[1].name
object_field_value = getattr(model_obj, field_name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM