2014-02-16 62 views
0

發佈相關數據我有這兩種模式:錯誤而與Tastypie

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.", 

,如果我從TransactionResource刪除

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

線我得到:

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

我在哪裏錯了?

回答

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不會想到你提供當你發佈一個交易事務中的順序。

+0

現在我得到了「error_message」:「(1048,」Column'order_id'不能爲空「)」 – Burak

+0

我添加了order = fields.ToOneField('OrderResource','order'),現在可以了。 – Burak