1๐
Two important points.
-
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)
-
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
- Problem launching docker-compose : python modules not installed
- How do I construct a Django form with model objects in a Select widget?
- Registered models do not show up in admin
- How to give initial value in modelform
0๐
you can user
django-filter
i think it not practical solution to edit get in serialiser
๐คfaruk
- When is it appropriate to use Django context processors?
- Error loading MySQLdb module: libmysqlclient.so.20: cannot open shared object file: No such file or directory
- Django cascade delete on reverse foreign keys
- How does this Man-In-The-Middle attack work?
Source:stackexchange.com