How to check ForeignKey reverse relation exists in Django?

Published 27 Jun, 2022

Reading time: 1 Mins


To check reverse relation exists in Django you need to use isnull keyword on queryset

To check foreign key exists in Django you can use isnull for that. Consider below example models for this blog.

class Profile(models.Model):
	user = models.CharField(max_length=200)

Class Message(models.Model):
	profile = models.ForeignKey(Profile, on_delete=models.CASCADE)

To get all of the user messages you will write like this.

profile.message_set.all()

or 

Message.objects.filter(profile=profile).all()

Both will give you the answers your looking for. But what if you wanted to list profile only when the messages are present?

Check if exists in ForeignKey

Profile.objects.filter(user=something, message__isnull=False).all()

Note: To return all other messages that this user not participated then use True.

This article published under development on django tags. If you wish to receive email from me when I post a new blog post then please subscribe to my newsletter.


You might also like