简体   繁体   English

Django模型迭代字段

[英]Django model iterate fields

how can I iterate and retrieve all fields of a django model? 如何迭代和检索django模型的所有字段?

I know that foo.item._meta.get_all_field_names() brings me all field names. 我知道foo.item._meta.get_all_field_names()给我带来了所有字段名称。 How can I access those fields (incl. their actual values) on a model instance? 如何在模型实例上访问这些字段(包括它们的实际值)? (Except the normal notation foo.fieldname ). (除了正常的符号foo.fieldname )。

I need this in order to build a custom output for my model including its manyTomany relations. 我需要这个来为我的模型构建一个自定义输出,包括它的manyTomany关系。 Any ideas? 有任何想法吗?

How about: 怎么样:

getattr(foo.__class__, <field_name>)

This should give you the field object, rather than the value in the given model instance. 这应该为您提供字段对象,而不是给定模型实例中的值。 If you want the value of the field in the given model insance you can call it like this: 如果你想要给定模型中的字段值,你可以像这样调用它:

getattr(foo, <field_name>)

This looks ugly but it will work: 这看起来很难看,但它会起作用:

for each in model_instance._meta.fields: 
    print each.value_from_object(model_instance)

That said, I have another suggestion. 那就是说,我有另一个建议。 Given that your requirement is to 鉴于您的要求是

to build a custom output for my model including its manyTomany relations. 为我的模型构建自定义输出,包括manyTomany关系。

how about serializing the instance to a suitable format (XML/JSON) and then working on that? 如何将实例序列化为合适的格式(XML / JSON),然后再进行处理? this avoids any dependency on _meta or any of the internal methods (which can possibly change). 这避免了对_meta或任何内部方法(可能会改变)的任何依赖。

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

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