gpt4 book ai didi

django - "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] in django rest framework while calling api in postman

转载 作者:行者123 更新时间:2023-12-05 01:31:22 26 4
gpt4 key购买 nike

当我使用 validated.pop() 函数从 orderitem 对象创建订单对象时,它工作正常。现在,我还有另一个需要创建的 BillingDetails 模型,它有一个指向 Order 模型的外键。

现在前端正在发送数据 block ,其中同时包含订单项数据和账单明细。我必须创建 Order 对象,同时创建 Orderitem 对象和 BillingDetails 对象。

我曾尝试编写此代码,但在 Postman 上调用 api 时出错。

enter image description here

我的模型:

class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.email

class OrderItem(models.Model):
order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items')
item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True)
quantity = models.IntegerField(default=1)


def __str__(self):
return f"{self.quantity} items of {self.item} of {self.order.user}"


class BillingDetails(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
order = models.OneToOneField(Order, on_delete=models.CASCADE, blank=True, null=True, related_name='billing_details')
first_name = models.CharField(max_length=50,blank=True,null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(blank=True, null=True)
phone = models.CharField(max_length=50,blank=True,null=True)
country = models.CharField(max_length=50,blank=True,null=True)
city = models.CharField(max_length=50,blank=True,null=True)
address = models.CharField(max_length=100,blank=True,null=True)
postal = models.CharField(max_length=50,blank=True,null=True)

def __str__(self):
return self.address

我的看法:

class AddtoOrderItemView(ListCreateAPIView):
permission_classes = [IsAuthenticated]
queryset = OrderItem.objects.all()
serializer_class = OrderSerializer

我的序列化器(最初):

class OrderSerializer(serializers.ModelSerializer):    
order_items = OrderItemSerializer(many=True)
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
class Meta:
model = Order
fields = ['id','user','start_date', 'ordered_date', 'ordered', 'order_items']
# depth = 1


def create(self, validated_data):
user = self.context['request'].user
order_items = validated_data.pop('order_items')
order = Order.objects.create(user=user,**validated_data)
for order_items in order_items:
OrderItem.objects.create(order=order,**order_items)
return order

到目前为止一切正常,我可以在创建订单项的同时订购对象。现在,当我弹出账单明细数据并尝试创建一个时,我得到了这个 Expected a dictionary, but got list. on Postman。

我的序列化器(现在)

class OrderSerializer(serializers.ModelSerializer):
billing_details = BillingDetailsSerializer(many=False)
order_items = OrderItemSerializer(many=True)
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
class Meta:
model = Order
fields = ['id','user','start_date', 'ordered_date', 'ordered', 'order_items','billing_details']
# depth = 1


def create(self, validated_data):
user = self.context['request'].user
order_items = validated_data.pop('order_items')
billing_details = validated_data.pop('billing_details')
order = Order.objects.create(user=user,**validated_data)
BillingDetails.objects.create(user=user,**billing_details)
for order_items in order_items:
OrderItem.objects.create(order=order,**order_items)
return order

如何解决这个问题??

最佳答案

根据您的 Postman 屏幕截图,您正在发送一个列表(用 [] 表示)。

"billing_details": [
{
"user":34,
"first_name":"Mylo",
"last_name":"Don"
}
]

如果您移除方括号以便您的 POST 请求包含一个字典(由 {} 表示),那么您应该不会再看到此错误。

"billing_details": {
"user":34,
"first_name":"Mylo",
"last_name":"Don"
}

如果您希望能够一次向 billing_details 发送多个请求,那么您可以像这样更新您的 serializers.py:

class OrderSerializer(serializers.ModelSerializer):
billing_details = BillingDetailsSerializer(many=True)

这也将使您的原始 POST 请求工作,因为传递 many=True 参数会导致序列化程序期待一个列表,在本例中它将是一个长度为 1 的列表。

关于django - "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] in django rest framework while calling api in postman,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66419789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com