How can I check if a class contains a specific attribute?

How can I check if a class contains a specific attribute?

In [14]: user = User.objects.get(pk=2)  

In [18]: user.__dict__  
Out[18]:   
{'date_joined': datetime.datetime(2010, 3, 17, 15, 20, 45),  
 'email': u'IloveDick@nwo.gov',  
 'first_name': u'',  
 'id': 2L,  
 'is_active': 1,  
 'is_staff': 0,  
 'is_superuser': 0,  
 'last_login': datetime.datetime(2010, 3, 17, 16, 15, 35),  
 'last_name': u'',  
 'password': u'sha1$44a2055f5',  
 'username': u'DickCheney'}  

In [25]: hasattr(user, 'username')  
Out[25]: True  

In [26]: hasattr(User, 'username')  
Out[26]: False  

I get a strange error when more attributes appear than I actually define. I want to conditionally stop this.

eg.

if not hasattr(User, 'karma'):
  User.add_to_class('karma', models.PositiveIntegerField(default=1)) 
+3
source share
4 answers

As far as I know, there is no method for Django models like hasattr (). But there is a way to check if the Django model has a specific field.

To test this, I would recommend that you refer to the Django shell (Python):

$> python manage.py shell

Now import the User model:

$> from django.contrib.auth.models import User

Get model meta-information:

$> opts = User._meta

To check the field, use the following command:

$> opts.get_field('username')

In the case of a user model, the following message will be printed:

<django.db.models.fields.CharField object at 0x1024750>

, , , FieldDoesNotExist. .

: b-list.org:

+9

, EAFP, , , , LBYL (Look Before You Leap).

Python Django, Django , __dict__. , Django - :

def django_model_has_field(model_class, field_name):
    return field_name in model_class._meta.get_all_field_names()
+7

User , . , , Model._meta.get_field(filename).

+1

For django 1.10 and more (after get_all_field_names is 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)
0
source

Source: https://habr.com/ru/post/1742676/


All Articles