Let’s say I have a set of Django Models:
class Article(models.Model):
title = models.CharField(max_length=100, default='')
content = models.TextField(default='', blank=False)
created_at = models.DateTimeField(auto_now=True)
creator = models.ForeignKey(User, null=True, blank=True)
score = models.ForeignKey('Score', blank=True, null=True)
points = models.ManyToManyField('Points')
class Score(models.Model):
value = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, null=True, blank=True)
class Points(models.Model):
value = models.DecimalField(max_digits=3, decimal_places=1)
caption = models.CharField(max_length=20, default='')
created_at = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
And now I somehow get an instance of a Score model (without actually knowing that this is Score model) and an instance of Points model (again, without knowing that this is Points model):
>>> type(s)
<class 'myapp.models.Score'>
>>> type(p)
<class 'myapp.models.Points'>
Now I can get access to a set of related Article instances via the following code:
>>> s.article_set
<django.db.models.fields.related.RelatedManager object at 0x10d1e8610>
>>> p.article_set
<django.db.models.fields.related.ManyRelatedManager object at 0x10d1e8850>
But this is the case where I know actual DB schema and I know that attributes are called article_set. In my case I do not know the actual DB scema. And I want to get all the RelatedManager attributes of the current model instance.
I think that it is possible to implement this via ._meta attribute but I didn’t manage to do that while trying. So I would probably need an actual working example of something like get_related_managers(self) method implementation.
This seems to work for me:
You will also have to loop through
self._meta.get_all_related_many_to_many_objects()if you want many to manys as well.UPD: In newer django versions,
_metadoes not have such methods, but the same can be done withself._meta.related_objectsandself._meta.many_to_many.