Last active
June 8, 2016 09:25
-
-
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.
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
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