我有这两个模型:
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")",
我哪里错了?
答案 0 :(得分:0)
您缺少事务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')
然后,当您发布交易时,tastypie不会指望您在交易中提供订单。