如何在django中获取模型字段类型进行验证[复制]

时间:2022-04-27 22:34:55

This question already has an answer here:

这个问题在这里已有答案:

I have tried:

我努力了:

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

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

我想要一些我可以使用的东西,如CharField,URLField,DoubleField等。

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

我怎么能得到像URLField这样的东西,以便我可以验证网址是否格式良好?

1 个解决方案

#1


0  

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.

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

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

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

Here's a simplified example:

这是一个简化的例子:

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

*好的,在这种情况下,因为函数总是返回一个常量值,你可以通过例如从源或func_code.co_consts元组中提取它来提取它。但显然这不会起作用;如果你想获得datetime.now()的值,它不会存储在now方法的任何地方,它会在你调用方法时动态生成。

#1


0  

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.

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

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

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

Here's a simplified example:

这是一个简化的例子:

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

*好的,在这种情况下,因为函数总是返回一个常量值,你可以通过例如从源或func_code.co_consts元组中提取它来提取它。但显然这不会起作用;如果你想获得datetime.now()的值,它不会存储在now方法的任何地方,它会在你调用方法时动态生成。