Django Tastypie - OneToOne关系POST不起作用

时间:2015-10-14 17:42:19

标签: python django tastypie

无论我尝试什么,我都会收到此响应错误。该方法似乎适用于ManyToOne Relationships但在OneToOne中失败。如果有人遇到并解决了这个问题,请提供帮助:

400 BAD REQUEST
{"error": "The 'order' field has no data and doesn't allow a default or null value."}

调试试用

  1. 尝试在“投放详细信息”中添加单独的主键“id”,因为我怀疑tastypie可能会失败,因为在创建相关字段之前无法生成订单ID。
  2. 删除了DeliveryDetails api中的订单字段,并尝试仅在订单资源中引用相关字段。
  3. 请求:

    curl -X "POST" "http://localhost:5000/core/api/v1/order/" \
        -H "Content-Type: application/json" \
        -d "{\"source\":\"W\",\"delivery_detail\":{\"email\":\"valery.flemister@yam.com\"}}"
    

    型号:

    class Order(models.Model):
        id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
        created_at = models.DateTimeField(
            verbose_name='created at',
            auto_now_add=True
        )
        updated_at = models.DateTimeField(
            verbose_name='updated at',
            auto_now=True
        )
        SOURCE_TYPES = (
            ('I', 'iOS'),
            ('A', 'Android'),
            ('W', 'Web'),
            ('N', 'Not Applicable')
        )
        source = models.CharField(
            verbose_name='order source',
            max_length=1,
            choices=SOURCE_TYPES,
            default='N'
        )
    class DeliveryDetail(models.Model):
        order = models.OneToOneField(
            to=Order,
            primary_key=True
        )
        email = models.EmailField(
            verbose_name='email address',
            max_length=255,
            blank=True,
            null=True
        )
    

    API:

    class OrderResource(ModelResource):
        delivery_detail = fields.ToOneField(
            to='core.api.v1_order.DeliveryDetailResource',
            attribute='deliverydetail',
            related_name='order',
            help_text='Delivery details',
            full=True
        )
    
        class Meta:
            queryset = Order.objects.all()
            resource_name = 'order'
    class DeliveryDetailResource(ModelResource):
        order = fields.ToOneField(
            to=OrderResource,
            attribute='order'
        )
    
        class Meta:
            queryset = DeliveryDetail.objects.all()
            resource_name = 'delivery_detail'
    

1 个答案:

答案 0 :(得分:0)

OneToOne字段不允许空值。所以当时,您想要创建交货,订单尚未创建,因此订单为空。先将订单请求拆分,然后再转发,或设置ToOneField属性null=True