2012-10-23 27 views
0

我有一个线程MPTT评论模型与我BlogItem模型中使用:Django的:如何创建对象,具有Tastypie

class MyComment(MPTTModel, Comment): 
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children') 
    class MPTTMeta: 
     order_insertion_by=['-submit_date'] 
    class Meta: 
     ordering=['tree_id','lft'] 

对于tastypie我做资源

class MyCommentResource(ModelResource): 

    # i tried to use this commented strings (and of course i created related resources) 
    #comment = fields.ForeignKey(CommentRosource, 'comment', null=True, full=True) 
    #site = fields.ForeignKey(SiteResource, 'site', null=True, full=True) 
    #content_type = fields.ForeignKey(ContentTypeResource, 'content_type', null=True, full=True) 
    #children = fields.ToManyField('self', 'children', null=True, full=True) 
    #content_object = GenericForeignKeyField({BlogItem: BlogItemResource}, 'content_object', null=True, full=True) 

    class Meta: 
     queryset = MyComment.objects.filter(level=0) 
     resource_name = 'myComment' 
     include_resource_uri = False 
     allowed_methods = ['get', 'post', 'put'] 
     include_resource_uri = False 
     filtering = { 
      'object_pk': ALL, 
      'level': ALL 
     } 
     authorization= Authorization() 

后,我已工作API GET请求FO MyComment模型(我可以看到所有评论(评论者的名字,注释文本,MPTT水平,分页等)

但是,当我试图让卷曲(或JS)erquest:

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"comment":"sdfsdfsdf"}' http://myhostname.com:80/api/v1/myComment/ > /tmp/err.html 

我得到错误“当前事务被中止,忽略,直到事务块结束指令”或其他错误(“DoesNotExist在/ API/V1/myComment /否提供的异常”,“无法分配无:” MyComment .content_type“不允许空值。” - 但在请求我POST {“content_type”:{“id”:“15”}}或链接到我的api content_type,也很好)。

其他更简单的模型(不一般的关系,但与ForeignKeys)我可以卷曲的请求并获得“201创造”的反应,所以我觉得我有错误相关的“通用”意见模型

我做错了吗?是否有任何文档或手册 - 如何通过tastypie为“通用”模型创建对象?

+0

您可以添加评论模型的来源吗? –

+0

我没有在MyComment模型中的任何额外的字段,我使用从contrib.Comment默认模型和MPTTModel继承 – Friendka

回答

0

如果您使用的是内置的Comment型号,那么GenericForeignKey不是可以为空的,这会抛出您看到的异常。资源上的GenericForeignKeyField指定null=True,导致Tastypie允许将空值传递给ORM。

您可以通过它的resource_uri指定GenericForeignKeyField的值,例如{"comment":"sdfsdfsdf", "content_object": "/api/v1/blog_item/1/"}

相关问题