简体   繁体   中英

Django Tastypie - OneToOne Relationship POST doesn't work

I keep getting this response error no matter what I try. The method seems to work perfectly for ManyToOne Relationships however fails in OneToOne. Please help if anyone has encountered and solved this before:

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

Debugging trials:

  1. Tried adding a separate primary key "id" in Delivery Details as I suspected that tastypie might be failing because it is not able to generate Order id before it creates the related fields.
  2. Removed the order field in the DeliveryDetails api and tried to reference the related field only in the Order Resource.

Request:

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\"}}"

Models:

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'

OneToOne Fields don't allow null values. So at the time, you want to create your Delivery, the order hasn't been created yet, so the order is null. Either split the request for Order first and then Delivery, or set the ToOneField attribute null=True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM