我有一个由140列组成的django模型,其中包含10种日期类型,60种字符类型,70种数字类型。
class SOA_detail(models.Model):
...
是否可以按数据类型进行分组,并将列名放在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
到目前为止,我知道要采用列名。
# 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)
感谢您抽出时间阅读我的问题。
答案 0 :(得分:6)
在python中有一个名为isinstance的内置方法,用于检查对象是否是特定类的实例,使用此方法可以这样做:
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)
答案 1 :(得分:3)
使用isinstance
。
例如:
>>> 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']