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

46 Views Asked by At

below is the description of the models:

  • I have a Law model
  • Each law has 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 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.

UPDATE:

Here are the models:

class Law(Timestamped):
    ...


class LatestAmendedLaws(Law):
    class Meta:
        proxy = True
        verbose_name = "Latest Amended Law"

class Version(Timestamped):
    law = models.ForeignKey(
        'Law',
        related_name='versions',
    )
    version_date = models.DateField(
        verbose_name=_("Version Date"),
    )


class Translation(Timestamped):
    law_version = models.ForeignKey(
        'Version',
        related_name='translations',
    )
    ...
1

There are 1 best solutions below

2
ruddra On

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.