0
votes

I have a modelviewset:

class ExpenseViewSet(ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, HasMetis]
    serializer_class = ExpenseSerializer

    def get_queryset(self):
        return Expense.objects.filter(recorded_by=self.request.user)

And a serializer:

class ExpenseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Expense
        fields = ["flat_id", "flat_group_id", "description", "notes", "amount"]

These are the fields that are POSTed to the viewset, but they are not sufficient to populate the object completely, so I need to add some more fields.

I've tried overriding the serializer, like so:

class ExpenseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Expense
        fields = ["flat_id", "flat_group_id", "description", "notes", "amount"]

    def create(self, validated_data):
        expense = Expense.objects.create(
            flat_id=validated_data["operations_flat"],
            flat_group_id=validated_data["operations_building"],
            description=validated_data["description"],
            notes=validated_data["notes"],
            amount=validated_data["amount"],
            recorded_by=self.request.user,
        )
        return expense

This, however, is never called (tested by sticking a print statement in the create function - it never runs). Apparently this is because of this question: Django Rest Framework serializer create() doesn't get triggered This explains the issue, but not how to solve my problem.

I'm not sure whether I need to override the is_valid function of the serializer, the create function of the serializer, or the create function of the viewset, or something else.

1
Might be you overrode something on the viewset that messes the default views behavior or the data you provided aren't valid (check the server response code and content).Linovia

1 Answers

0
votes

You should override the perform_create() on viewset something like this and pass in your extra data for object creation:

def perform_create(self, serializer):
    serializer.save(user=self.request.user)

Reference : Save and deletion hooks: https://www.django-rest-framework.org/api-guide/generic-views/#genericapiview (search perform_create in this page for faster lookup)