Sh VavilenT
Sh VavilenT

Reputation: 337

How to filter an empty list? Many to many relationship

I filter as follows:

queryset = queryset.prefetch_related(
            Prefetch('level', queryset=Level.objects.filter(id=level)))

In this case, empty lists remain:

{
   ...
    "level": []
   ...
},
{
    ...
    "level": [
        2
    ]
    ...
}

I tried to filter like this:

queryset = queryset.prefetch_related(
            Prefetch('level',queryset=Level.objects.filter(id=level).exclude(id__isnull=True)))

But it didn't help.

I also want to know if it is possible to get a value without lists?

{
    ...
    "level": 2
    ...
}

Upvotes: 2

Views: 269

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

You should not filter on the Prefetch object, since then it is "too" late. Then you filter out elements. You should filter the queryset with:

queryset.filter(level=level).prefetch_related(
     Prefetch('level', queryset=Level.objects.filter(id=level)))
)

You can furthermore annotate the value of Level, and then use that as a field:

from django.db.models import F

queryset.filter(level=level).annotate(
    level_value=F('level')
)

Then in the serializer, you can use an IntegerField for example that takes as source='level_value':

from rest_framework import serializers

class MyModelSerializer(serializers.ModelSerializer)
    level = IntegerField(source='level_value')

    class Meta:
        model = MyModel

Upvotes: 1

Related Questions