问题
I am trying to override create method to make a post request but i am stuck, here is my code
class Order(models.Model):
street_number = models.PositiveIntegerField(blank=True, null=True)
street_name = models.CharField(max_length=250, null=True, blank=True)
class Seller(models.Model):
order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='seller_order',blank=True, null=True)
first_name = models.CharField(max_length=250, null=True, blank=True)
last_name = models.CharField(max_length=250, null=True, blank=True)
class OrderSerializer(serializers.ModelSerializer):
sellers = SellerSerializer()
class Meta:
model = Order
fields = '__all__'
def create(self, validated_data):
order = Order.objects.create(**validated_data)
seller_validated_data = validated_data.pop('sellers')
if seller_validated_data:
seller_obj = Seller.objects.create(order=order)
seller_obj.first_name = seller_validated_data.get('first_name')
seller_obj.middle_name = seller_validated_data.get('middle_name')
seller_obj.last_name = seller_validated_data.get('last_name')
order.save()
return order
My json in postman i am sending like below
{
"street_number":11,
"street_name":"dfd",
"seller":{
"first_name":"kk",
"last_name":"dfdf"
}
}
But i am unable to create seller object with a relation of order, please help me
来源:https://stackoverflow.com/questions/64324443/how-to-post-onetoone-field-in-django-rest-framework-using-overwrite-create-metho