9👍
as far as I know there is no method like hasattr() for Django models. But there is a way to check if a Django model has a certain field.
To test this I would recommend you to access the Django (Python) shell:
$> python manage.py shell
Now import the User model:
$> from django.contrib.auth.models import User
Get the meta information of the model:
$> opts = User._meta
To check a field use the following command:
$> opts.get_field('username')
In case of the User model there will be printed out a message like this:
<django.db.models.fields.CharField object at 0x1024750>
If the field you are looking for is not part of the model a FieldDoesNotExist will be thrown. With this knowledge you should be able to check the existence of a field programmatically.
You can read more about that here: b-list.org: Working with models
7👍
I agree with the comments made in the question about EAFP, but conversely there are some scenarios when you need to LBYL (Look Before You Leap).
An approach for Python classes in general won’t work for Django models, as Django’s metaclass magic means that fields are not contained in the model class’ __dict__
. So, specifically for Django models, you can do something like the following function:
def django_model_has_field(model_class, field_name):
return field_name in model_class._meta.get_all_field_names()
- [Django]-Testing a Django app in many separate threads
- [Django]-Convert python object to protocol buffer object
1👍
The User class doesn’t have a username attribute, because model fields are added by the metaclass at initialization time. But you can check that a model defines a particular field by using Model._meta.get_field(filename)
.
- [Django]-How to populate database fields when model changes in django
- [Django]-Python Piston equivalent for consuming RESTful APIs?
- [Django]-Django flatpages and images
- [Django]-Why can't Fabric fabfile see Django settings?
- [Django]-Url contains spaces in django v3
0👍
For django 1.10 and greater (after get_all_field_names was deprecated):
def get_or_create_field(self, field_name, type):
if field_name not in [f.name for f in self._meta.get_fields()]:
self.add_to_class(field_name, type)
return self._meta.get_field(field_name)
- [Django]-Django Temporary Images
- [Django]-Python model inheritance and order of model declaration
- [Django]-Django on IIS, process exited unexpectedly
- [Django]-What's your favorite way to test the javascript in your djangoapp?