在 Django 中获取模型的字段 [英] Get model's fields in Django

查看:32
本文介绍了在 Django 中获取模型的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 Django 模型,我试图列出它的所有字段.我已经看到一些使用 _meta 模型属性执行此操作的示例,但是 meta 前面的下划线是否表示 _meta 属性是私有属性,不应直接访问?... 因为,例如,_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?

_meta 是这个规则的例外吗?它是否稳定且可以使用,或者访问它是否被认为是不好的做法?或者是否有函数或其他方法可以在不使用 _meta 属性的情况下内省模型的字段?下面是一些链接列表,显示了如何使用 _meta 属性执行此操作

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

非常感谢任何建议.

django 对象获取/设置字段

http://www.djangofoo.com/80/get-list-model-fields

如何自省 django 模型字段?

推荐答案

_meta 是私有的,但相对稳定.正在努力对其进行形式化、记录并删除下划线,这可能发生在 1.3 或 1.4 之前.我想会努力确保东西向后兼容,因为无论如何很多人都在使用它.

_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

我相信这将返回一个 Field 对象列表.要从实例中获取每个字段的值,请使用 getattr(instance, field.name).

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).

更新:Django 贡献者正在开发 API 以替换 _Meta 对象,作为 Google Summer of Code 的一部分.见:
- https://groups.google.com/forum/#!topic/django 开发人员/hD4roZq0wyk
- https://code.djangoproject.com/wiki/new_meta_api

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆