ResultSet with query on multiple models

16 views
Skip to first unread message

Benoit Dupont

unread,
Aug 23, 2019, 7:19:35 AM8/23/19
to Django users

Hello,

I've played a lot of time with Django and it's a great tool for basic query but I don't figure out how to play with Django to do a query spanning between a lot of models.

This is the query I do to display all Animals and their corresponding Vaccines with Encounter.status 'in-progress' and the Immunization date is in the futur.


    def current_with_futur_vaccines(self):

        return (

            Encounter.objects.filter(

                status="in-progress").filter(

                subject__immunizations__recorded__gte=datetime.now(),

            )

            .select_related("subject")

            .prefetch_related("subject__immunizations", "location")

        )


 {% for immunization in object.subject.immunizations.all %}

         {{ immunization }}

    {% endfor %}


The things is when I want to list the Immunizations from the query I get all the Immunizations for this animal and not only the Immunizations that have to take place in the futur like I said in the query. I guess it's because of the .all() and what I need is more something like Encounter.subject.immunization_set()


This is the model

  

    class Animal(models.Model):

        name = models.CharField(max_length=250)

    

    class Encounter(models.Model):

            subject = models.ForeignKey(Animal, on_delete=models.PROTECT)

            status = models.CharField(max_length=11)

        

    class Vaccine(models.Model):

            name = models.CharField(max_length=250)


    class Immunization(models.Model):

        subject = models.ForeignKey(

            Animal, on_delete=models.PROTECT, related_name="immunizations"

        )

        recorded = models.DateTimeField(default=timezone.now)

        vaccine = models.ForeignKey(Vaccine, on_delete=models.PROTECT)


Thanks for your help

Benoit Dupont

unread,
Aug 24, 2019, 6:54:12 AM8/24/19
to Django users
I think I have figured it out. 
I have to play with models.Prefetch() to restrict the results from the prefetch_related()

Can someone confirm this is the right way to do it ?

Thanks

Catalina Popescu

unread,
Aug 24, 2019, 8:18:16 AM8/24/19
to Django users
Hey, Benoit

You could set up a filter on your admin.py file. Like writing:

class Immunization(admin.ModelAdmin):
    list_filter = ('vaccine', 'recorded')
Reply all
Reply to author
Forward
0 new messages