Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-REST Serializer: Queryset does not filter PrimaryKeyRelatedField results

So I have a serializer that looks like this

class BuildingsSerializer(serializers.ModelSerializer):
    masterlisting_set = serializers.PrimaryKeyRelatedField(many=True, 
                                    queryset=Masterlistings.objects.all())

and it works great

serializer = BuildingsSerializer(Buildings.objects.get(pk=1))
serializer.data 

produces

OrderedDict([
    ("masterlistings_set", [
        "0a06e3d7-87b7-4526-a877-c10f54fa5bc9",
        "343643ac-681f-4597-b8f5-ff7e5be65eef",
        "449a3ad2-c76c-4cb8-bb86-1be72fafcf64",
    ])
])

but if I change the queryset in the serializer to

class BuildingsSerializer(serializers.ModelSerializer):
     masterlistings_set = serializers.PrimaryKeyRelatedField(many=True, queryset=[])

I still get the same exact result back.

 OrderedDict([
    ("masterlistings_set", [
        "0a06e3d7-87b7-4526-a877-c10f54fa5bc9",
        "343643ac-681f-4597-b8f5-ff7e5be65eef",
        "449a3ad2-c76c-4cb8-bb86-1be72fafcf64",
    ])
])

Is this supposed to be happening? Am I using querysets incorrectly? I used [] as an easy example to show that no matter what I put in nothing changes.

Please any insight would be invaluable

It should be noted that masterlistings has a primary key relationship that points to buildings. So a masterlisting belong to a building.

like image 744
Charles Haro Avatar asked Apr 20 '16 21:04

Charles Haro


1 Answers

As pointed out by @zymud, queryset argument in PrimaryKeyRelatedField is used for validating field input for creating new entries. Another solution for filtering out masterlistings_set is to use serializers.SerializerMethodField() as follows:

class BuildingsSerializer(serializers.ModelSerializer):
    masterlisting_set = serializers.SerializerMethodField()

    def get_masterlisting_set(self, obj):
        return MasterListing.objects.filter(building=obj).values_list('pk',flat=True)
like image 111
Amit Jaiswal Avatar answered Sep 20 '22 05:09

Amit Jaiswal