如何从django中的db模型获取字段类型字符串

时间:2021-11-26 06:45:20

I am doing the following:

我正在做以下事情:

model._meta.get_field('g').get_internal_type

Which returns the following:

返回以下内容:

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

I only want the know that this field is "URLField" . How do I extract that from this output?

我只想知道这个字段是“URLField”。如何从此输出中提取?

Note: I am doing this so that I can do validation on the fields. For example if a url , I want to check if it is well formed.

注意:我这样做是为了我可以对字段进行验证。例如,如果是网址,我想检查它是否格式正确。

2 个解决方案

#1


22  

If you were doing this:

如果你这样做:

model._meta.get_field('g').get_internal_type()

You could not possibly get that as a result.

你不可能得到那样的结果。

Instead, you are doing this:

相反,你这样做:

model._meta.get_field('g').get_internal_type

Which, as explained here, does not call the method, it just refers to the method as a bound method object. The return value is not part of that bound method object, it's created by the method when the method is called. So, you have to call it. So you need the parentheses.

如此处所解释的那样,它不会调用该方法,它只是将该方法称为绑定方法对象。返回值不是该绑定方法对象的一部分,它是在调用方法时由方法创建的。所以,你必须打电话给它。所以你需要括号。

#2


1  

The answer is to call the method instead:

答案是调用方法:

my_type = field.get_internal_type()

#1


22  

If you were doing this:

如果你这样做:

model._meta.get_field('g').get_internal_type()

You could not possibly get that as a result.

你不可能得到那样的结果。

Instead, you are doing this:

相反,你这样做:

model._meta.get_field('g').get_internal_type

Which, as explained here, does not call the method, it just refers to the method as a bound method object. The return value is not part of that bound method object, it's created by the method when the method is called. So, you have to call it. So you need the parentheses.

如此处所解释的那样,它不会调用该方法,它只是将该方法称为绑定方法对象。返回值不是该绑定方法对象的一部分,它是在调用方法时由方法创建的。所以,你必须打电话给它。所以你需要括号。

#2


1  

The answer is to call the method instead:

答案是调用方法:

my_type = field.get_internal_type()