I need to dynamically inspect the python types of all the fields within my models in an app, that is, given that I have:
class MyModel(model.Model):
field1 = model.CharField(max_length=20)
field2 = modelf.IntegerField()
...
fieldn = models.BooleanField()
I need to accomplish something like:
>>> for field in MyModel._meta.fields:
••• field.type
•••
<type 'str'>
<type 'int'>
...
obviously field.type
is something that does not exist, but I need to retrieve the built-in type the model is supposed to accept when the model is created/updated. ForeignKeys and M2M are a special case that can be ignored for this question.
Thanks for any help.
Sorry, Field
s do not contain such information. The to_python
method is used to convert values into the expected Python data type, and it's free to return whatever it likes.
You can build a type map yourself, obviously limited to field types you know about:
FIELD_PYTHON_TYPES = {
'AutoField': int,
'BooleanField': bool,
'CharField': unicode,
'DateField': datetime.date,
'DateTimeField': datetime.datetime,
'DecimalField': decimal.Decimal,
'FloatField': float,
'IntegerField': int,
'BigIntegerField': int,
... # etc.
}
and look up types from it with get_internal_type
:
for field in MyModel._meta.fields:
FIELD_PYTHON_TYPES[field.get_internal_type()]
But even, for example, built-in NullBooleanField
can use two types ( bool
and NoneType
), so it's far from a general solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.