gpt4 book ai didi

python - Django(1.11) 休息框架在嵌套序列化器中发布 user.id

转载 作者:行者123 更新时间:2023-12-01 08:56:10 24 4
gpt4 key购买 nike

当用户在模型中创建送货地址和产品数据时,我想在后台获取 user.id,但出现此错误
ull value in column "ordered_by_id" violates not-null constraint
DETAIL: Failing row contains (66, 5051, tetsst, 2018-10-11, f, null).

这意味着 user.id 由于某种原因没有被添加到模型中。

我的模型.py

class Product(models.Model):
price = models.FloatField()
name = models.CharField(default='gift', max_length=512)
ordered_by = models.ForeignKey(User, null=False)
date = models.DateField(auto_now_add=True)
purchased = models.BooleanField(default=False)

def __str__(self):
return self.name


class Delivery(models.Model):
address = models.CharField(max_length=256)
city = models.CharField(max_length=128)
country = models.CharField(max_length=128)
zip_code = models.IntegerField() #gotta change that one to charfield
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'."
" Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=16, blank=False)
delivered = models.BooleanField(default=False)
product = models.ForeignKey(Product)

我的序列化器.py

class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = (
"name",
"price",
)

class ProductDeliverySerializer(serializers.ModelSerializer):
product = ProductSerializer()

class Meta:
model = Delivery
fields = (
"address",
"city",
"country",
"zip_code",
"phone_number",
"product",
)

def create(self, validated_data):
product_data = validated_data.pop('product')
print(validated_data, product_data)
product = Product.objects.create(**product_data)
delivery = Delivery.objects.create(product=product, **validated_data)
return delivery

当我打印/测试验证数据时,它实际上显示“表单”/POST 已完成 {'address': 'address here', 'city': 'City is here', 'country': 'Country is here', 'zip_code': 3333, 'phone_number': '+19991234567', 'ordered_by': <SimpleLazyObject: <User: testuser>>}
产品数据 OrderedDict([('name', 'tetsst'), ('price', 5051.0)])
的输出

我的观点.py

class ProductList(generics.ListCreateAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer

def perform_create(self, serializer):
serializer.save(ordered_by=self.request.user)


class DeliveryList(generics.ListCreateAPIView):
queryset = Delivery.objects.all()
serializer_class = ProductDeliverySerializer

def perform_create(self, serializer):
serializer.save(ordered_by=self.request.user)

最佳答案

问题出在 product = Product.objects.create(**product_data) 中。产品数据不包含任何用户对象。它不见了。这可能是你如何构造输入 JSON 的问题。将验证数据中的 ordered_by 添加到 Product_data。像这样的事情:

product_data['ordered_by'] = validated_data.pop('ordered_by')

关于python - Django(1.11) 休息框架在嵌套序列化器中发布 user.id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52756946/

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