[Answered ]-Populate parent field from url kwarg in a nested serializer in Django REST Framework

1👍

You can work with a simple mixin that will patch both the get_queryset and the perform_create method:

class FilterCreateGetMixin:
    filter_field_name = None
    filter_kwarg_name = None

    def get_filter_dict(self):
        return {self.filter_field_name: self.kwargs[self.filter_kwarg_name]}

    def get_queryset(self, *args, **kwargs):
        return (
            super().get_queryset(*args, **kwargs).filter(**self.get_filter_dict())
        )

    def perform_create(self, serializer):
        serializer.save(**self.get_filter_dict())

then we can make a mixin, specifically for the category for example:

class CategoryFilterMixin(FilterCreateGetMixin):
    filter_field_name = 'catalog'
    filter_kwarg_name = 'catalog_pk'

and mix this in the viewset/API view:

class EpicSerializer(serializers.ModelSerializer):
    class Meta:
        model = Epic
        exclude = ['catalog']


class EpicsViewSet(
    CategoryFilterMixin, mixins.CreateModelMixin, viewsets.GenericViewSet
):
    serializer_class = EpicSerializer
    permission_classes = (IsAuthenticated, CatalogPermissions)

The advantage of this is that we can easily mix this into all other views where we have a category_pk in the path.

Leave a comment