How to post OneToOne field in django rest-framework using overwrite create method

落爺英雄遲暮 提交于 2021-01-05 07:31:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!