python 如何以编程方式获取 Django 模型字段的 max_length?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1829216/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:09:21  来源:igfitidea点击:

How can I programmatically obtain the max_length of a Django model field?

pythondjangodjango-modelsoop

提问by Mat

Say I have a Django class something like this:

假设我有一个像这样的 Django 类:

class Person(models.Model):
    name = models.CharField(max_length=50)
    # ...

How can I programatically obtain the max_lengthvalue for the namefield?

如何以编程方式获取max_lengthname字段的值?

回答by Ben James

Person._meta.get_field('name').max_lengthwill give you this value. But having to use _metasuggests this is something you shouldn't do in normal usage.

Person._meta.get_field('name').max_length会给你这个值。但是必须使用_meta表明这是您在正常使用中不应该做的事情。

Edit: as Carl pointed out, this naming is misleading and it does seem quite acceptable to use it: http://www.b-list.org/weblog/2007/nov/04/working-models/

编辑:正如卡尔指出的那样,这个命名具有误导性,使用它似乎是完全可以接受的:http: //www.b-list.org/weblog/2007/nov/04/working-models/

回答by Gines Hidalgo

The question is regarding models, but for people trying to do the same for forms (that's how I ended up in this thread), I think this approach is quite simple and clear:
1. In a template:
{{form.name.field.max_length}}

2. In python code (e.g. in the view)
form.name.field.max_length

问题是关于模型,但对于试图对表单做同样的事情的人(这就是我在这个线程中结束的方式),我认为这种方法非常简单明了:
1. 在模板中:
{{form.name.field.max_length}}

2. 在 python 代码中(例如在视图中)
form.name.field.max_length