Tastypie - invested resources are updated instead of created on POST

I am trying to POST a resource, which consists mainly of a list of child resources. Here are my resources:

class MovementResource(ModelResource): transactions = fields.ToManyField('stock.api.TransactionResource', 'transaction_set', related_name='movement', full=True) class Meta: queryset = Movement.objects.all() resource_name = 'movement' always_return_data = True authorization = Authorization() class TransactionResource(ModelResource): movement = fields.ToOneField(MovementResource, 'movement') product = fields.ToOneField(ProductResource, 'product', full=True) class Meta: queryset = Transaction.objects.all() resource_name = 'transaction' authorization = Authorization() 

This represents the movement of various products in inventory. A movement form is just a list of inline rows, one for each transaction. It does not use django forms at all.

My problem is that when I try to perform a POST movement indicating the list of transactions that will be created, I find that instead of inserting new transactions, Tastypie updates the existing one. This is the JSON for the POST request representing the movement with only one transaction:

 { 'transactions': [ { 'product': '/api/v1/product/3/', 'quantity': '1' } ] } 

The JSON response shows that the movement was created, but the transaction has an identifier that existed before and had the same product and quantity. The FK Movement in this transaction object has been updated to indicate a newly created Movement. Response data:

 { 'date': '2013-02-07 ···', 'id': '66', 'resource_uri': '/api/v1/movement/66/', 'transactions': [ { 'date': '2013-01-30 ···', # Should be the same as parent movement date 'id': '30', 'movement': '/api/v1/movement/66/', 'product': { ··· product resource data ··· }, 'quantity': '1', 'resource_uri': '/api/v1/transaction/30/', } ] } 

Am I missing something? Should Tastypie create nested resources that are this POST at the end of the list? I tried using ForeignKey and ToOneField for MovementResource to see if this would make any difference, but without success. (I actually could not find the difference between the two.)

Thanks!

+4
source share
1 answer

I have the same problem.

After long hours of working with it, I found a workaround that forces POST on the linked resource: if you pass null for the primary key of the embedded resource, then tastypie POSTs is new, instead of updating, the existing one.

If you do a POST, you should get the behavior you are looking for:

 { 'transactions': [ { 'product': '/api/v1/product/3/', 'quantity': '1', 'id': null } ] } 
+7
source

All Articles