Last active
April 26, 2022 11:13
-
-
Save bentappin/8617378 to your computer and use it in GitHub Desktop.
Checking if an object is a foreign key anywhere in Django.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
.