【问题标题】:Django: how to create object with TastypieDjango:如何用 Tastypie 创建对象
【发布时间】:2012-10-23 12:03:58
【问题描述】:

我有一个线程 mptt cmets 模型可与我的 BlogItem 模型一起使用:

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']

我为美味派制作了资源

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()

之后,我为 MyComment 模型的 GET 请求提供了工作 api(我可以看到所有 cmets(评论者的姓名、评论文本、mptt 级别、分页等)

但是当我尝试制作 curl(或 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 at /api/v1/myComment/ 未提供异常”、“无法分配无:“MyComment.content_type”确实不允许空值。” - 但在请求中我 POST {"content_type":{"id":"15"}} 或链接到我的 api 中的 content_type 也很好用)。

对于其他更简单的模型(没有通用关系,但使用 ForeignKeys)我可以发出 curl 请求并获得“201 created”响应,所以我认为我有与“通用”cmets 模型相关的错误

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

【问题讨论】:

  • 你能添加你的评论模型的来源吗?
  • MyComment 模型中没有任何附加字段,我使用从 contrib.Comment 默认模型和 MPTTModel 继承

标签: python django tastypie


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 2012-04-21
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多