2014-03-27 41 views
1

刚刚推出的Django tastypie和无法发送data.I有一个Django模型,很难理解为什么Django的tastypie POST失败,出现500内部错误

class OrderItem(SmartModel): 
    shopping_id = models.CharField(max_length=255,db_index=True) 
    quantity = models.IntegerField() 
    item = models.ForeignKey(Item) 
    option = models.ForeignKey(OptionalItem,null=True,blank=True) 
    toppings_and_extras = models.ManyToManyField(ToppingsAndExtra,null=True, blank=True) 

和tastypie资源,

class OrderItemResource(ModelResource): 
    item = fields.ToOneField(ItemResource,'item',null=False,blank=False,full=True) 
    option = fields.ToOneField(OptionResource,'option',null=True,blank=True,full=True) 
    toppings_and_extras = fields.ToManyField(ToppingResource,'toppings_and_extras',null=True,blank=True,full=True) 
    class Meta: 
     queryset = OrderItem.objects.all() 
     resource_name = 'order' 
     authorization = Authorization() 
     always_return_data =True 

我执行测试POST如tastypie文档所示,

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"shopping_id":"([email protected]$PJWUCQ4WEG3%CL0RSDPUD%EDQ!EG$81^WXSV6^URBC0OO45OC(IV)QW7WC(W0GD9)N&5HXLA1)8M1IHGWQ4A&P1","quantity":"5","item":"/api/v1/menu_item/1/","option":"/api/v1/options/1/","created_by":"/api/v1/user/1/","modified_by_id":"/api/v1/user/1/","toppings_and_extra":"[]"}' http://localhost:8000/api/v1/order/ 

请求响应错误“当前事务被中止”,查看日志,错误为null value in column "created_by_id" violates not-null constraint。这是我不明白,因为我想加入"created_by":"/api/v1/user/1/"照顾的问题。我做得不对,我的研究是有限的,因为我似乎无法理解发生了什么问题。链接到文档中的有用信息也是值得赞赏的。

回答

0

要访问任何关系字段,您必须在ModelResource中定义它。

class OrderItemResource(ModelResource): 
    created_by = fields.ToOneField(UserResource,'created_by') 
    [...] 

    class Meta: 
     queryset = OrderItem.objects.all() 
     resource_name = 'order' 
     authorization = Authorization() 
     always_return_data =True 

你为什么这样做的原因是,Tastypie必须知道模型的ModelResource定义:资源名称,查询集和他人之间的授权访问。没有它,Tastypie会忽略它。

如果你还没有定义UserResource,你应该这样做。

我看到您正在使用所有型号的基础模型:“SmartModel”。我认为最适合你的将是创建基础模型资源来继承。 “SmartModelResource”,你将在那里定义需要的字段。

class SmartModelResource(ModelResource): 
    created_by = fields.ToOneField(UserResource,'created_by') 
    [...] 


class OrderItemResource(SmartModelResource): 
    [...] 

    class Meta: 
     queryset = OrderItem.objects.all() 
     resource_name = 'order' 
     authorization = Authorization() 
     always_return_data =True 
+0

我看你还用'modified_by'这个字段是不是现在这个错误? –

+0

是的,这是一个造成麻烦的错字。接得好。将批准你的答案 –

相关问题