Lets say I have the following models setup:
class X(models.Model):
...
class Y(models.Model):
x = models.ForeignKey(X)
class Z(models.Model):
x = models.ForeignKey(X)
Now, in a method, I want to get all the Y
objects and Z
objects that are related to a given X
object. I want to hit my database once, and return a combined queryset. Right now, I am doing it like this:
x = X.objects.get(pk=1)
queryset = []
for cls in [Y, Z]:
queryset += list(cls.objects.filter(x=x))
Note: running it through a loop is important because there are quite a few models in my actual code, so looping keeps the whole thing DRY. How can I do this? Thanks.