覆盖序列化器中的创建

时间:2019-02-21 07:38:10

标签: django python-3.x django-rest-framework

我在序列化程序中覆盖了create方法,但似乎在执行POST请求时并没有进入此功能:

我的序列化器:

class ElsUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = ElsUser
        fields = ['id', 'first_name', 'last_name', "email"]
        read_only_fields = ['id']

class RequisiteItemSerializser(serializers.ModelSerializer):
    created_by = ElsUserSerializer()

    class Meta:
        model = RequisiteItem
        fields = ['id', 'enrollable', 'completed_within_days', 'completed_within_type','date_completed_by', 'created_by' ]
        read_only_fields = ['id']


class RequisiteSerializer(serializers.ModelSerializer):
    created_by = ElsUserSerializer()
    items = RequisiteItemSerializser(many=True)

    class Meta:
        model = Requisite
        fields = ('id', 'name', 'description', 'items', 'enrolments', 'created_by', 'timestamp')
        read_only_fields = ['id']
        depth = 1

    def create(self, validated_data):
        print("SELF INTITIAL DATA", self.initial_data)
        helper = RequisiteHelper()
        requisite = helper.create(self.initial_data,self.context['request'])
        print("LOGGES IN USER", self.context['request'].user.username)

        return requisite

我已将方法移至单独的帮助程序类:

我的助手班:

class RequisiteHelper:
    def create(self, initial_data, context):
        name = initial_data['name']
        description = initial_data['description']
        items = initial_data['items']
        enrolments = initial_data['enrolments']
        requisite = Requisite.objects.create(name=name, description=description, created_by=context.user)
        self.create_items(requisite, items, context)
        self.create_enrolments(requisite, enrolments)
        requisite.save()
        return requisite

def create_items(self, requisite, items, context):
    for item in items:
        requisite_item = RequisiteItem()
        enrollable = Enrollable.objects.get(id=item.enrollable.id)
        requisite_item.enrollable = enrollable
        requisite_item.created_by = context.user
        requisite_item.completed_within_days = item.completed_within_days
        cw_type = CompletedWithinType.objects.get(short_name = item.completed_within_type)
        requisite_item.completed_within_type = cw_type
        requisite_item.save()
        requisite.items.add(requisite_item)

def create_enrolments(self, requisite, enrolments):
    for enrolment in enrolments:
        requisite.add(enrolment)

当我通过邮寄方法创建“必需品”时,它会一直显示created_by是必需的。我通过覆盖create方法自动将created_by保存为登录用户。打印语句也不会显示。我可能做错了什么?

在views.py中,我有:

   class ListCreateRequisite(generics.ListCreateAPIView):
       serializer_class = RequisiteSerializer
       queryset = Requisite.objects.all()

1 个答案:

答案 0 :(得分:1)

您的create方法未调用,因为调用created_by时需要对serailizer.is_valid()的模型字段进行验证,而对require字段的模型字段进行了验证。您需要在调用序列化程序之前或在运行时分配该值,甚至可以在模型定义中更改created_by要求。这样您就可以绕过这个陷阱了。