Django Rest Framework modelviewset-在创建之前更新字段

时间:2018-12-17 21:43:27

标签: django django-rest-framework django-rest-viewsets

我有一个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)

还有一个序列化器:

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

这些是发布到视图集的字段,但是它们不足以完全填充对象,因此我需要添加更多字段。

我已经尝试过覆盖序列化程序,就像这样:

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

但是,它从未被调用(通过在create函数中粘贴一条打印语句进行测试-它永远不会运行)。显然是因为这个问题:Django Rest Framework serializer create() doesn't get triggered这说明了问题,但没有解决我的问题。

我不确定是否需要重写序列化器的is_valid函数,序列化器的create函数或视图集的create函数,或其他。

1 个答案:

答案 0 :(得分:0)

您应该在视图集上覆盖perform_create(),如下所示,并传递额外的数据以创建对象:

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

参考文献:保存和删除挂钩: https://www.django-rest-framework.org/api-guide/generic-views/#genericapiview(在此页面中搜索perform_create以加快查找速度)