Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if OneToOneField is None in Django

I have two models like this:

class Type1Profile(models.Model):     user = models.OneToOneField(User, unique=True)     ...   class Type2Profile(models.Model):     user = models.OneToOneField(User, unique=True)     ... 

I need to do something if the user has Type1 or Type2 profile:

if request.user.type1profile != None:     # do something elif request.user.type2profile != None:     # do something else else:     # do something else 

But, for users that don't have either type1 or type2 profiles, executing code like that produces the following error:

Type1Profile matching query does not exist. 

How can I check the type of profile a user has?

Thanks

like image 697
John Bright Avatar asked Aug 11 '10 22:08

John Bright


1 Answers

To check if the (OneToOne) relation exists or not, you can use the hasattr function:

if hasattr(request.user, 'type1profile'):     # do something elif hasattr(request.user, 'type2profile'):     # do something else else:     # do something else 
like image 96
joctee Avatar answered Sep 24 '22 13:09

joctee