[Django]-How to check django model data type?

6👍

There is a builtin method in python called isinstance which checks if an object is an instance of a specific class or not, using this method you can do it like this:

for model_field in SOA_detail._meta._fields():
  if isinstance(model_field, CharField):
      char_fields.append(model_field.name)
  elif isinstance(model_field, IntegerField):
      num_fields.append(model_field.name)
  elif isinstance(model_filed, DateTimeField):
      date_field.append(model_field.name)
👤Sassan

3👍

Use isinstance.

For example:

>>> from django.db import models
>>> from django.contrib.auth.models import User
>>> [f.name for f in User._meta.fields if isinstance(f, models.CharField)]
['password', 'username', 'first_name', 'last_name', 'email']
>>> [f.name for f in User._meta.fields if isinstance(f, models.DateTimeField)]
['last_login', 'date_joined']
>>> [f.name for f in User._meta.fields if isinstance(f, models.IntegerField)]
[]
>>> [f.name for f in User._meta.fields if isinstance(f, models.AutoField)]
[u'id']

Leave a comment