How to filter the latest amended laws in django admin site?

below is the description of models:

  • I have a Law model
  • Each law many Versions
  • Each version has many Translations
  • Each translation has many annotations

I want to get the latest amended laws in the django admin site. So, I created a proxy model of Law.

and in the the admin file of law I have this:

@admin.register(LatestAmendedLaws)
class LatestAmendedLawsAdmin(admin.ModelAdmin):
    list_display = ("id", "rs_number", "created")

    def get_queryset(self, request):
        latest_translation_datetime = Translation.objects.latest("created").created
        return (
            super()
            .get_queryset(request)
            .filter(created__gte=latest_translation_datetime)
        )

this script doesn't return the correct latest amended laws. because it filters based on the created field of law. but it should be based on the latest created/updated date of translations that are associated with the law.

Maybe you can try like this:

django.db.models import SubQuery, OuterRef

query = Translation.objects.filter(law_version__law_id=OuterRef('pk')).order_by('created')

LatestAmendedLaws.objects.annotate(max_date=Sunquery(query.values('created')[:1])).filter(versions__translations__created=F('max_date'))

Here I am annotating the maximum created time of Translation and annotate it with LatestAmendedLaws queryset using Subquery. Then I ran a filter based on the annotated fields.

Back to Top