Skip to content

Instantly share code, notes, and snippets.

@ddaan
Last active June 8, 2016 09:25
Show Gist options
  • Save ddaan/a370fd2dde72a67b682ddbd537a91fbb to your computer and use it in GitHub Desktop.
Save ddaan/a370fd2dde72a67b682ddbd537a91fbb to your computer and use it in GitHub Desktop.
Add this method to your django model to quickly retrieve every object that links to it.
def used_in(self):
"""
Method to return all objects where this object is linked from by
a foreign key or many-to-many relationship
Be aware that:
- Calling this method wil result in as many queries as there are
relations, so use this carefully.
- It will only see the models linking directly to this model. So watch
out for inherited models. Calling used_in on a childobject will
return 0 objects when a field will link to the parentobject
:return: mixed list of django model instances
"""
object_list = []
for relation_field in self._meta._relation_tree:
kwargs = {relation_field.name: self.pk}
object_list.extend(relation_field.model.objects.filter(**kwargs))
return object_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment