【问题标题】:Error while posting relational data with Tastypie使用 Tastypie 发布关系数据时出错
【发布时间】:2014-02-16 09:25:30
【问题描述】:

我有这两个模型:

class Order(models.Model):
    shop = ForeignKey(Shop)
    date_modified = DateTimeField(auto_now=True)

    class Meta:
        db_table = 't_order'

class Transaction(models.Model):
    order = ForeignKey('Order')
    quantity = IntegerField()
    item = ForeignKey(Item)
    date_modified = DateTimeField(auto_now=True)

    class Meta:
        db_table = 't_transaction'

还有两个资源:

class OrderResource(ModelResource):
    shop = fields.ToOneField(ShopResource, 'shop')
    transactions = fields.ToManyField('TransactionResource','transaction_set', full=True)

    class Meta:
        queryset = Order.objects.all()
        resource_name = 'order'
        authentication = Authentication()
        authorization = Authorization()
        allowed_methods = ['post', 'get']
class TransactionResource(ModelResource):
        order = fields.ToOneField('OrderResource', 'order')
        item = fields.ToOneField('ItemResource', 'item')
    class Meta:
        queryset = Transaction.objects.all()
        resource_name = 'transaction'
        authentication = Authentication()
        authorization = Authorization()
        allowed_methods = ['post', 'get']

我将此数据发布到

http://127.0.0.1:5000/api/order/

{
 "shop": "/api/shop/1/",
 "transactions": [
        {
                "item": "/api/item/6/",
                "quantity" : 2
        }
    ]
}

我收到以下错误:

"error_message": "Transaction has no order.",

如果我删除

order = fields.ToOneField('OrderResource', 'order')

我得到的来自 TransactionResource 的行:

"error_message": "(1048, "Column 'order_id' cannot be null")",

我哪里错了?

【问题讨论】:

    标签: django django-models tastypie


    【解决方案1】:

    您在事务 ToManyField 定义中缺少 related_name 属性。 而不是:

    transactions = fields.ToManyField('ttests.api.TransactionResource','transaction_set', full=True)
    

    你应该使用:

    transactions = fields.ToManyField('ttests.api.TransactionResource','transaction_set', full=True, related_name='order')
    

    那么当你发布交易时,tasticpie 不会期望你在交易中提供订单。

    【讨论】:

    • 现在我又得到了 "error_message": "(1048, "Column 'order_id' cannot be null")"
    • 我添加 order = fields.ToOneField('OrderResource', 'order') 现在可以了。
    猜你喜欢
    • 1970-01-01
    • 2012-07-30
    • 2014-09-15
    • 2015-06-03
    • 2014-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多