N+1 queries in SerializerMethodField

16 views
Skip to first unread message

m0nte cr1st0

unread,
Jun 24, 2022, 10:08:09 AMJun 24
to Django users
I have this `view`

```
    def get_queryset(self) -> QuerySet[Good]:
        ....
        qs = (
            Good.objects.values('brand_id', 'brand__name')
            .annotate(
                ....
            )
            .prefetch_related(Prefetch('history', StocksHistory.objects.filter(Q(**subquery_filter_args))))
            .order_by('-total_sales')
        )
        return qs

```
and serializer
```
class ExtendedBrandSerializer(serializers.ModelSerializer):
    ...
    history = serializers.SerializerMethodField()

    class Meta:
        model = Good
        fields = (
            ...
            'history',
        )

    def get_history(self, good: dict) -> dict:
      ....

      return StocksHistorySerializer(
        StocksHistory.objects.extra(select={'day': 'date( snap_at )'})
        .values('day')
        .filter(history_filter_query)
        .annotate(
            ....
        ),
        many=True,
      ).data
```

**Relation**: `StocksHistory (*) -> (1) Good`.

I have `N+1` queries in `SerializerMethodField`. How can I fix it?

Perhaps there is a way to move annotate from serializer to view?

The bottom line is that I also need the history key in the response, which will contain a list of these child objects.

Queries - https://gist.github.com/dima-dmytruk23/0183014d76ad25f4e2a0ca87ec225a10

Also can I use RAW SQL for it maybe?
Reply all
Reply to author
Forward
0 new messages