summary
In Django, what is the simplest way to determine if there are any objects in our database that refer to a given object?
details
Consider this minimal example from Django's Related objects reference:
from django.db import models
class Reporter(models.Model):
pass
class Article(models.Model):
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
How can we determine if there are any objects, so not only Article
objects, that point to a given Reporter
object, either through a OneToOneField
, a ForeignKey
, or a ManyToManyField
?
In other words, we want to determine if there are any reverse relations to the given object.
For Article
it is easy, we can just get e.g. reporter.article_set.count()
, but other models may be added later which also point to Reporter
, and these will also have to be taken into account.
example use-case
An example use case is where we want to prevent modification as soon as an object is being referenced by any other object. Or we could use it to enforce a kind of behavior similar to the on_delete=models.PROTECT
mechanism.