Thursday, June 27, 2019

Beginner's question regarding prefetch_related

Dear Django community,

I have a data model that looks like the following:

class Submission(models.Model):
   ...

class Assessment(models.Model):
   submission = models.ForeignKey(
       Submission, on_delete=models.CASCADE, related_name='assessments')
   time_stamp = models.DateTimeField()

And I would like to do something simple such as computing a list of pairs of submissions and their most recent assessments:

qs = Submission.objects.prefetch_related('assessments')
xs = [(s, s.assessments.latest('time_stamp')) for s in qs.all()]

This seems to be inefficient because the assessments table seems to be queried for each submission.
I've read about prefetch_related and tried to use it as above but it doesn't seem to have any effect.
I suppose this is because I try to use 'latest'?
Is prefetch_related applicable in this case at all or do I need to resort to a different technique like a raw SQL query?

Thanks in advance!

Simon

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e38b499f-d54b-4f6a-874b-a95af0b778b0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment