Azima
Azima

Reputation: 4151

django using aggregate() and distinct() together

I have a filterset that has following attributes:

dosFromGte = filters.DateFilter(method="search_by_dos_from_gte", lookup_expr="gte")
dosToLte = filters.DateFilter(method="search_by_dos_from_lte", lookup_expr="lte")

# One of these methods:

def search_by_dos_from_lte(self, queryset: Chart, name: str, value: str) -> Chart:
    return queryset.annotate(max_dos=Min("diagnosis__dos_from")).filter(max_dos__lte=value)

# using annotate and aggregate Min().

I need to run few annotations and then only fetch distinct ids.

queryset = self.filter_queryset(self.get_queryset().exclude(state__in=repo_exclude))
queryset = queryset.annotate(
            ChartId=F("chart_id")
        ).values(
            "ChartId"
        ).distinct("id")

When I apply these filters ?clientId=11&project=56&dosFromGte=2023-08-17&dosToLte=2023-08-19 this tries to run Min() and then distinct on ids.

This gives NotImplementedError("aggregate() + distinct(fields) not implemented.")

So I tried to work around a bit and

queryset.values(
            "id", "ChartId"
        )
# remove duplicate charts based on pk, i.e. id
df = df.drop_duplicates('id')
df = df.drop('id', axis=1)

which kind of felt like a hack and dirty work around.

Is there a cleaner ORM way to do it?

Upvotes: 0

Views: 41

Answers (0)

Related Questions