[Fixed]-Django Request Framework 'ManyRelatedField' object has no attribute 'queryset' when modifying queryset in get_fields

1๐Ÿ‘

Two important points.

  1. When a queryset is filtered from the view for a user, all the foreign key objects retrieval will yield only the objects for the particular user. So no need to filter for the user inside get_fields.

    class StoryList(generics.ListAPIView):
        serializer_class = StorySerializer
    
         def get_queryset(self):
             # consider there is login check before code is reaching here
             # since this filtered by the user and any susbquent 
             # foreign key objects will belong only to this user
             return Story.objects.filter(user=self.request.user)
    
  2. Once the filtering for a user happens, then you can use another serializer or SerializerMethodField to construct the data accordingly. The below code should work for your case.

     class UserSerializer(serializers.HyperlinkedModelSerializer):
         class Meta:
             # Allow only url and id
             fields = ['id', 'url']
             extra_kwargs = {'url': {'view_name': 'user-detail'}}
    
     class FeatureSerializer(serializers.HyperlinkedModelSerializer):
         class Meta:
             fields = ['id', 'url']
             extra_kwargs = {'url': {'view_name': 'feature-detail'}}
    
     class PhotoSerializer(serializers.HyperlinkedModelSerializer):
         class Meta:
             fields = ['id', 'url']
             extra_kwargs = {'url': {'view_name': 'photo-detail'}}
    
    class StorySerializer(serializers.HyperlinkedModelSerializer):
        user = UserSerializer(read_only=True) 
        comments = serializers.HyperlinkedRelatedField(read_only=True, 
                               view_name='comment-detail', many=True)
        # this work because of related names
        features = FeatureSerializers(many=True)
        photos = PhotoSerializers(many=True)
        # add tags serializer as well
        text = serializers.CharField()
    
        class Meta:
             fields = ['id', 'users', 'photos', 'features', ...]
    
๐Ÿ‘คKracekumar

0๐Ÿ‘

Instead of overriding get_fields method, you can try drf-writable-nested package, this will help to serialize nested relationships much easier and hand orm fields directions better.

๐Ÿ‘คauvipy

0๐Ÿ‘

you can user
django-filter

i think it not practical solution to edit get in serialiser

๐Ÿ‘คfaruk

Leave a comment