Hi there,
On Thursday, 27 June 2019 22:09:29 UTC+3, swimmer wrote:
-- I think you can use values() to do a group by. Something along these lines should be able to do it in 3 queries:
from django.models import Max
# aggregate grouping by submission then get those assessment objects
latest_assessments = Assessment.objects.values('id', 'submission', latest=Max('time_stamp'))
assessments = Assessment.objects.filter(id__in=[a['id'] for a in latest_assessments])
# map submission_id to the latest assessment
assessments = {a.submission_id: a}
# match latest assessment to submission
submissions = Submission.objects.all()
xs = [(s, assessments.get(s.id, None)) for s in submissions]
On Thursday, 27 June 2019 22:09:29 UTC+3, swimmer wrote:
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/c5366579-3bf5-4fff-be2b-3e869620171a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment