在Django中获取模型的字段 [英] Get model's fields in Django
问题描述
_meta是否为此规则的例外?它是稳定的和准备使用还是被认为是不好的做法访问它?或者是否使用函数或其他方式来内省模型的字段而不使用_meta属性?以下是使用_meta属性
的一些链接列表,任何建议都非常感谢。
http://www.djangofoo.com/80/get-list-model-fields
_meta
是私有的,但相对稳定。正在努力使其正式化,记录并删除可能在1.3或1.4之前发生的下划线。我想象会努力确保事情向后兼容,因为很多人一直在使用它。
如果你特别关心兼容性,写一个函数它需要一个模型并返回字段。这意味着如果将来某些事情发生变化,您只需要更改一个功能。
def get_model_fields(model):
return model._meta.fields
我相信这会返回一个字段
对象。要从实例中获取每个字段的值,请使用 getattr(instance,field.name)
。
更新:Django贡献者正在使用API来替换_Meta对象作为Google Summer of Code的一部分。请参阅:
- https://groups.google .com / forum /#!topic / django-developers / hD4roZq0wyk
- https://code.djangoproject.com/wiki/new_meta_api
Given a Django model, I'm trying to list all of its fields. I've seen some examples of doing this using the _meta model attribute, but doesn't the underscore in front of meta indicate that the _meta attribute is a private attribute and shouldn't be accessed directly? ... Because, for example, the layout of _meta could change in the future and not be a stable API?
Is _meta an exception to this rule? Is it stable and ready to use or is it considered bad practice to access it? Or is there a function or some other way to introspect the fields of a model without using the _meta attribute? Below is a list of some links showing how to do this using the _meta attribute
Any advice is much appreciated.
http://www.djangofoo.com/80/get-list-model-fields
How to introspect django model fields?
_meta
is private, but it's relatively stable. There are efforts to formalise it, document it and remove the underscore, which might happen before 1.3 or 1.4. I imagine effort will be made to ensure things are backwards compatible, because lots of people have been using it anyway.
If you're particularly concerned about compatibility, write a function that takes a model and returns the fields. This means if something does change in the future, you only have to change one function.
def get_model_fields(model):
return model._meta.fields
I believe this will return a list of Field
objects. To get the value of each field from the instance, use getattr(instance, field.name)
.
Update: Django contributors are working on an API to replace the _Meta object as part of a Google Summer of Code. See:
- https://groups.google.com/forum/#!topic/django-developers/hD4roZq0wyk
- https://code.djangoproject.com/wiki/new_meta_api
这篇关于在Django中获取模型的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!