DRF-如何正确更新前导密钥

时间:2019-07-10 16:23:13

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

自从我的请求发送“客户ID”(例如:12)以来,我在更新User对象时遇到了麻烦,但是我的序列化器y正在等待命令

更清楚地说,这是我收到的消息: 无效数据。希望有字典,但要完整。

我要完成的是从我的用户(是ForeingKey)更新我的客户字段

这是我的viewset.py:

def update(self, request, *args, **kwargs):
    try:
        customer = BankCustomer.objects.filter(id=request.data.get('customer'))
        serializer = UserSerializer(customer, data=request.data)
    except BankCustomer.DoesNotExist:
        return Response(None, status=status.HTTP_400_BAD_REQUEST)
    if serializer.is_valid():
        serializer.save()
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    return Response(serializer.data, status=status.HTTP_200_OK)

user serializers.py:

class UserSerializer(serializers.ModelSerializer):
    customer = BankCustomerSerializer()
    email = serializers.EmailField()

    class Meta:
        model = User
        fields = ('id', 'email', 'name', 'lastname', 'type', 'customer', 'is_blocked')


    def update(self, instance, validated_data):
        instance.customer = validated_data.get("customer", instance.customer)
        instance.email = validated_data.get("title", instance.email)
        instance.name = validated_data.get("name", instance.name)
        instance.lastname = validated_data.get("lastname", instance.lastname)

        return instance

客户序列化器:

class BankCustomerSerializer(serializers.ModelSerializer):
    users = serializers.PrimaryKeyRelatedField(many=True, source='customer_r', queryset=User.objects.all(), default='')

    class Meta:
        model = BankCustomer
        fields = ('id', 'customer', 'ruc', 'address', 'phone', 'users')

1 个答案:

答案 0 :(得分:0)

如果我没记错的话,您只想发送更新的客户ID字段,但是想要在响应中获取整个客户实例。

实现此目的的一种方法是使用序列化程序RelatedField,如下所示:

class CustomerListingField(serializers.RelatedField):

    def to_representation(self, instance):
        return instance

    def to_internal_value(self, data):
        return Customer.objects.get(id=data)

    def get_queryset(self):
        return Customer.objects.all()

然后,在UserSerializer中替换:

customer = BankCustomerSerializer()

与此:

customer = CustomerListingField()