Python 如何获取 Django 模型字段对象的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51905712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the value of a Django Model Field object
提问by HuLu ViCa
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?
我使用field_object = MyModel._meta.get_field(field_name)
. 如何获取字段对象的值(内容)?
回答by awesoon
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
:
这与以下内容相同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)
回答by JPG
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
回答by root
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:
在模型 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)