I have these two models:
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'
and two resources:
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']
I am posting this data to
http://127.0.0.1:5000/api/order/
:
{
"shop": "/api/shop/1/",
"transactions": [
{
"item": "/api/item/6/",
"quantity" : 2
}
]
}
I am getting following error:
"error_message": "Transaction has no order.",
if I remove
order = fields.ToOneField('OrderResource', 'order')
line from TransactionResource I am getting:
"error_message": "(1048, "Column 'order_id' cannot be null")",
Where am I wrong?
You are missing the related_name attribute in the transactions ToManyField definition. instead of:
transactions = fields.ToManyField('ttests.api.TransactionResource','transaction_set', full=True)
you should use:
transactions = fields.ToManyField('ttests.api.TransactionResource','transaction_set', full=True, related_name='order')
Then tastypie will not expect that you provide the order inside the transaction when you're posting a transaction.