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
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