我在serializer
中使用了Writable Nested Serializer并使用了create
这样的方法:
class OrderSerializer(serializers.ModelSerializer):
billing = BillingSerializer()
class Meta:
model = Order
fields = '__all__'
def create(self, validated_data):
billing_data = validated_data.pop('billing')
order = Order.objects.create(**validated_data)
Billing.objects.create(**billing_data)
return order
我可以创建嵌套数据。但当我得到一个视图时,它显示如下:
{
"id": 1,
"billing": {},
"quantity": 3,
"delivery_date": "2017-01-27T15:44:40Z",
"base_rate": "90.00",
"is_delivered": false,
"created_at": "2017-01-26T07:26:53.194450Z",
"updated_at": "2017-01-26T07:26:53.194495Z",
"user_id": 1
}
空白字典用于结算。我的模型如下:
class Billing(models.Model):
paid_status = models.BooleanField(default=False)
total_billed = models.DecimalField(default=90.00, max_digits=6, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('created_at',)
verbose_name = 'Billing'
verbose_name_plural = 'Billings'
class Order(models.Model):
user_id = models.ForeignKey('auth.User', related_name='orders', on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(validators=[MaxValueValidator(10)])
delivery_date = models.DateTimeField(default=datetime.now()+timedelta(days=1))
base_rate = models.DecimalField(default=90.00, max_digits=6, decimal_places=2)
is_delivered = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
billing = models.TextField()
class Meta:
ordering = ('created_at',)
verbose_name = 'Order'
verbose_name_plural = 'Orders'
def __str__(self):
return self.id
这是我的oderView:
class OrderViewSet(viewsets.ModelViewSet):
queryset = Order.objects.all()
serializer_class = OrderSerializer
permission_classes = (permissions.IsAuthenticated, permissions.IsAdminUser,)
如何获得我预期的数据?
答案 0 :(得分:0)
使用结算作为外键解决了此问题:
在order
模型中:
billing = models.ForeignKey(Billing, related_name='orders', on_delete=models.CASCADE)
正如它所示:
/ api / orders /上的IntegrityError(1048,“列'billing_id'不能 空“)
我在OrderSerializer
中改变了创建方法:
def create(self, validated_data):
billing_data = validated_data.pop('billing')
billing = Billing.objects.create(**billing_data)
billing.save()
order = Order.objects.create(billing_id=billing.id, **validated_data)
return order