如何获取在django中验证的模型字段类型 [英] how to get model field type for validation in django

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

问题描述

我试过:

field = model._meta.get_field_by_name(field_name)[0]
my_type = field.get_internal_type

这不起作用,因为它会返回一些绑定的方法,如:

This does not work as it gives back some bound method like:

<bound method URLField.get_internal_type of <django.db.models.fields.URLField:my_url>>

我想要一些可以像CharField,URLField,DoubleField等一样世界的东西。

I want something I can world with like CharField, URLField, DoubleField, etc.

如何获取类似URLField的东西,以便我可以验证URL是否格式良好?

How can I get something like URLField so that I can validate if the url is well formed for example?

推荐答案

在Python中,如果要调用函数或方法,则必须在参数周围使用括号。如果没有参数,您只需使用空括号。

In Python, if you want to call a function or method, you have to use parentheses around the arguments. If there are no arguments, you just use empty parentheses.

您正在做的只是引用方法本身,而不是调用它。

What you're doing is just referencing the method itself, not calling it.

这是一个简化的例子:

>>> def foo():
...     return 3
>>> foo()
3
>>> foo
<function __main__.foo>

您不能从函数中提取结果;你必须叫它。*

You can't "extract" the result from the function; you have to call it.*

所以,在你的例子中,只需将第二行改为:

So, in your example, just change the second line to this:

my_type = field.get_internal_type()






* OK,在这种情况下,因为函数总是返回一个常量值,可以通过例如从源或 func_code.co_consts 元组。但显然这将无法正常工作如果你想得到 datetime.now()的值,它不会存储在现在的任何地方方法,当您调用方法时,它会在飞行中生成。


* OK, in this case, because the function just always returns a constant value, you could extract it by, e.g., pulling it from the source or the func_code.co_consts tuple. But obviously that won't work in general; if you want to get, say, the value of datetime.now(), it's not stored anywhere in the now method, it's generated on the fly when you call the method.

这篇关于如何获取在django中验证的模型字段类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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