Skip to main content
Bumped by Community user
[Edit removed during grace period]
Source Link
M3RS
  • 413
  • 4
  • 11
Source Link
M3RS
  • 413
  • 4
  • 11

Django, filtering on reverse foreign key

We have Projects, which can each have many Entries. We want a report where we see the completion_date of the newest Entry associated with a given Project. However, we only want to consider Projects that have Entries after "2022-1-15".

Is this the best we can do or is there a more compact way to achieve this?

models.py

class Entry(models.Model):
    project = models.ForeignKey(related_name='entries')
    completion_date = models.DateTimeField()


class Project(models.Model):
    name = models.TextField(blank=True)

views.py

project_ids = Entry.objects \
    .filter(completion_date__gte=datetime.date("2022-1-15")) \
    .select_related('project') \
    .values_list('project', flat=True)


projects = Project.objects \
    .filter(id__in=set(project_ids), name=None) \
    .prefetch_related('entries') \
    .annotate(last_completion_date=Max('entries__completion_date'))

template.html

{% for project in projects %}
    {{project.name}}: {{project.last_completion_date}}
{% endfor %}