Is there a way to neatly return a queryset’s values_list of related objects from many objects’ related managers at the same time without having to write a loop ?
In other words this query:
Hospital.objects.first().treatments.all().values_list('treatment_appointments', flat=True)
will return me a list of PKs that will look something like this:
<QuerySet [1, 32, 35, 21, 30, 28, 29, 13, 56, 58, 59, 60, 61, 66, 67, 87]>
Is it possible to write such query that will return the actual objects instead of those PKs?
here are the models:
class Treatment(models.Model): name=models.TextField() class Hospital(models.Model): treatments = models.ManyToManyField(Treatment, related_name='treatments') class Appointment(models.Model): treatment = models.ForeignKey(Treatment, related_name='appointment_treatments')
Advertisement
Answer
You can filter with:
hospital = Hospital.objects.first() Appointment.objects.filter(treament__hispital=hospital)