Skip to content

Instantly share code, notes, and snippets.

@bentappin
Last active April 26, 2022 11:13
Show Gist options
  • Save bentappin/8617378 to your computer and use it in GitHub Desktop.
Save bentappin/8617378 to your computer and use it in GitHub Desktop.
Checking if an object is a foreign key anywhere in Django.
from django.db import models
class Thing(models.Model):
# [ snip ]
def is_deletable(self):
for rel in self._meta.get_all_related_objects():
if rel.model.objects.filter(**{rel.field.name: self}).exists():
return False
return True
@bentappin
Copy link
Author

If there's a nicer/more idiomatic way to do this please do fork and let me know!

I probably shouldn't be relying on anything in _meta.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment