Expand a QuerySet with all related objects

class Hobby(models.Model):
    name = models.TextField()


class Person(models.Model):
    name = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    hobbies = models.ManyToManyField(Hobby, related_name='persons')


class TShirt(models.Model):
    name = models.TextField()
    person = models.ForeignKey(
        Person,
        related_name='tshirts',
        on_delete=models.CASCADE,
    )


class Shirt(models.Model):
    name = models.TextField()
    person = models.ForeignKey(
        Person,
        related_name='shirts',
        on_delete=models.CASCADE,
    )


class Shoes(models.Model):
    name = models.TextField()
    person = models.ForeignKey(
        Person,
        related_name='shoes',
        on_delete=models.CASCADE,
    )

Given a queryset of Person, e.g.

Person.objects.order_by('-created_at')[:4]

How can I make a queryset which also includes all the objects related to the Person objects in that queryset?

The input QuerySet only has Person objects, but the output one should have Hobby, Shoes, TShirt, Shirt` objects (if there are shirts/tshirts/shoes that reference any of the people in the original queryset).

I've only been able to think of solutions that rely on knowing what the related objects are, e.g. TShirt.objects.filter(person__in=person_queryset), but I would like a solution that will work for all models that reference Person without me having to one-by-one code each query for each referencing model.

Вернуться на верх