[Answered ]-How to filter by table-A from table-B (table-A is linked to table-B, not the otherwise)

1👍

There is no need to define extra ForeignKeys or add extra fields to the Movement table. We can work with a Subquery expression [Django-doc]:

from django.db.models import OuterRef, Subquery


class CaseAdmin(admin.ModelAdmin):
    def get_queryset(self, *args, **kwargs):
        return (
            super()
            .get_queryset(*args, **kwargs)
            .annotate(
                last_direction=Subquery(
                    Movement.objects.filter(case_id=OuterRef('pk'))
                    .order_by('-date')
                    .values('direction')[:1]
                )
            )
        )

    list_filter = [LastDirectionFilter]

with as LastDirectionFilter:

from django.contrib import admin


class LastDirectionFilter(admin.SimpleListFilter):
    title = 'Last direction'
    parameter_name = 'last_direction'

    def lookups(self, request, model_admin):
        return [
            ('S', 'Sent'),
            ('R', 'Returned'),
            ('-', 'No movement yet'),
        ]

    def queryset(self, request, queryset):
        value = self.value()
        if value == '-':
            return queryset.filter(last_direction=None)
        elif value is not None:
            return queryset.filter(last_direction=value)
        return queryset

here we thus filter on our annotation that can be None if there is no movement yet, or 'S' or 'R'.

Leave a comment