3

I have a django model consist of 140 columns which contain 10 date types, 60 char types, 70 number types.

class SOA_detail(models.Model):
    ...

Is there a way to group up by data types and place the column name in a list.

char_fields = [] # storage for character fields column name
num_fields  = [] # storage for number fields column name
date_fields = [] # storage for date fields column name

So far I know is to take the column name.

 # take all field names from model
 for model_field in SOA_detail._meta._fields():
      if #datatype is char: ---??
          char_fields.append(model_field.name)
      elif #datatype is num: ---??
          num_fields.append(model_field.name)
      elif #datatype is date: ---??
          date_field.append(model_field.name)

Thank you for your time reading my question.

2 Answers 2

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)
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']
1
  • this is a great example, sir. Jan 13, 2014 at 7:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.