[Fixed]-Django rest PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=App.objects.all()) is not JSON serializabl

1👍

def get_apps(self, obj):
    if obj.username != "admin":
        return
    else:
        apps = UserAppSerializer(read_only=True,
                                 many=True)
        return apps

This function is incorrect.
that function is getting user instance as parameter obj and is supposed to return value for app field.
However the function doesn’t do anything with the user instance and instead of returning value return an empty instance of UserAppSerializer.

also
app = models.ManyToManyField(Application)
This should’ve been called apps for clarity
apps = models.ManyToManyField(Application)

Then your serializer function can be re-written like this

def get_apps(self, obj):
    if obj.username != "admin":
        return
    else:
        return UserAppSerializer(instance=obj.apps, 
                                 read_only=True, many=True).data
👤Ramast

Leave a comment