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.