0

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',
    )
    ...
Mahdi Jafari
  • 347
  • 6
  • 22

1 Answers1

1

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.

ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Thanks @ruddra, I copied the code but it returns almost all the laws, not the amended laws. Could help me a bit more? – Mahdi Jafari Jan 27 '23 at 08:45
  • Maybe I am missing something here. Because I have annotated the latest created time with the queryset and filtering with it. Maybe you can see the annotated value ( by adding `values('max_date')` to see if it is correct or not. If you need more conditions for filtering, I would prefer if you share your full models and some example outputs. – ruddra Jan 27 '23 at 08:49