保存/ POST django-rest-framework时使用相关字段的值

时间:2018-04-19 11:14:59

标签: django django-rest-framework

我试图找到一个发布字符串值并将其保存到外键字段而不是使用pk的方法。

我的模特:

class CustomUser(models.Model):
    username = models.CharField(max_length=500, unique=True)  

    def __str__(self):
        return self.username



class Order(models.Model):
    ordernumber = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True)
    amount = models.FloatField(null=True, blank=True)

    def __str__(self):
          return "{0}".format(self.ordernumber)

我的序列化器:

class OrderSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')


    class Meta:
        model = Order
        fields = ('id','username', 'ordernumber', 'amount')
        read_only_fields = ('id')

使用GET时,一切都运行正常,但我似乎无法修复POST方法。

我试图像这样覆盖create方法:

def create(self, validated_data):

    username = validated_data.pop('username')
    order = Order.objects.create(**validated_data)
    order.user = CustomUser.objects.get(username=username)
    order.save()

    return order

但我在username = validated_data.pop('username')行:Exception Value:'username'

上收到了KeyError

1 个答案:

答案 0 :(得分:0)

对嵌套字段使用source时,数据可以validated_data['parent_field']['child_field']访问。试试这个:

def create(self, validated_data):

    user_data = validated_data.pop('user')
    username = user_data.pop('username')
    order = Order.objects.create(**validated_data)
    order.user = CustomUser.objects.get(username=username)
    order.save()

    return order