My DB contains passport images of different people. Something like:
class Person(models.Model):
pass
class PersonPhoto(models.Model):
date_captured = models.DateField()
person = models.ForeignKey(Person, null=False)
I want to extract for each person all of the images from the latest date he was photographed. So if person A has photos from August 5, 5, 9, 11, 11, and person B has images from August 7, 9, 13, 13, 19, 19 then I want to fetch both images from August 11 for person A, and both images from August 19 for person B.
The way I'm currently doing that is something like:
specific_dates_queryset = Q()
for photo in PersonPhoto.objects.all().values('person_id').annotate(max_date=Max('date_captured')):
specific_dates_queryset |= Q(person_id=photo["person_id"], date_captured=photo["max_date"])
for photo in PersonPhoto.objects.filter(specific_dates_queryset).order_by("person_id"):
print(f"image for person {photo.person_id}, of date {photo.date_captured}")
The idea is to first find the latest date of a photo for each person, and then in a new query to fetch these images for these people from these dates.
Is there a simpler solution that does everything within the DB and avoids redundant queries and data fetching?
from Django - retrieve objects from latest date for each group - PersonPhoto
No comments:
Post a Comment