Reputation: 3774
I'm getting a list of the fields of my model like this:
c = Client.objects.all().first()
fields = c._meta.get_all_field_names()
How can I get a list of the datatypes (CharField, Int, etc) of those fields? Is there an easier way than looking up the get_internal_type
property on each field?
Thanks!
Upvotes: 0
Views: 536
Reputation: 10563
You can use:
raw_list = c._meta.get_fields_with_model()
When you do raw_list = c._meta.get_fields_with_model()
raw_list contains something like:
((<django.db.models.fields.AutoField: id>, None), (<django.db.models.fields.TextField: signature>, None) etc...
To get a "parsed" list that only contains the name of the datatype we can do:
[item[0].__class__.__name__ for item in raw_list._meta.get_fields_with_model()]
or using get_internal_type:
[item[0].get_internal_type() for item in raw_list._meta.get_fields_with_model()]
In both ways you'll get a list like :
['AutoField', 'TextField', 'TextField', 'FloatField', 'CharField', 'BooleanField', 'IntegerField', 'ImageField', 'BooleanField'...
Just the code:
raw_list = c._meta.get_fields_with_model()
parsed_list = [item[0].__class__.__name__ for item in raw_list._meta.get_fields_with_model()]
Upvotes: 1