Django One to One Exists

Published 1 Jul, 2020


How to check Django ORM One-To-One objects exists in queryset object.

When working with Django ORM we often encounter the problem with whether the object exist or not. For example in One-To-One relationship there is no API to check if objects exist in object.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    is_subscribed = models.BooleanField(default=False)

Above is the simple snippet that extends the User object with One-To-One relationship. We often access this object in views or templates like this request.user.profile.is_subscribed but that works when the profile objects attached to request.user.

So how to check the attribute exists in that object. We can use hasattr Python keyword to check the existence.

if hasattr(request.user, 'profile'):
    # Profile attribute exists in the request.user.
    print(request.user.profile.is_subscribed.

I work at Dialoggbox as Software Engineer. I write tutorials on web application development. SuperCharged Coder who believes the perfect code is no code at all.

This article published under development on django tags. Please support me by subscribing to my Newsletter. By subscribing you will not miss any future articles in this category.