代码之家  ›  专栏  ›  技术社区  ›  user7304253

如何在Django中映射对象?

  •  2
  • user7304253  · 技术社区  · 7 年前

    假设我的POST方法中有三个字段- field1 , field2 , field3 字段3 在添加到数据库期间应具有相同的值。因此不需要添加例如 field2=2 , field3=2 手动。我只能补充 field1=1 , 字段2=2 然后 字段3=2

    意见。py:

    class UserObject(GenericAPIView):
    
        def get_serializer_class(self, *args, **kwargs):
            if self.request.method == 'POST':
                return ObjectPostSerializer
            return ObjectSerializer
    
        def post(self, request, user_id):
    
            serializer = ObjectPostSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save(user_id=user_id)
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    

    序列化程序。py:

    class ObjectPostSerializer(serializers.ModelSerializer):
    
        def __init__(self, *args, **kwargs):
            super(ObjectPostSerializer, self).__init__(*args, **kwargs)
    
            for key in self.fields:
                self.fields['field3'].required = False
    
        class Meta:
    
            model=Object
            field3 = model.field2
    
            fields = ('__all__')
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Brown Bear    7 年前

    可能你可以用简单的逻辑,排除 field3 并将其设置为 save 模型方法

    在序列化程序中:

    class ObjectPostSerializer(serializers.ModelSerializer):
    
        class Meta:
            model=Object
            exclude = ('field3', )
    

    class Object(model.Model):
        # YOU FIELDS DECLARE HERE
    
        def save(self, *args, **kwargs):
            if not self.pk:
                self.field3 = self.field2
            super(Object, self).save(*args, **kwargs)