Django,mongodb,Tastypie-nonrel:ForeignKey列表

时间:2012-02-24 16:58:26

标签: django api mongodb tastypie

在我的Django-mongodb模型上,我希望有一个包含对其他对象的引用的listField的对象。这是我想要实现的一个例子:

models.py

class Comment(models.Model):
    title = models.CharField(max_length=50)
    body = models.CharField(max_length=50)

class Post(models.Model):
    name = models.CharField(max_length=50)
    commentList = ListField(models.ForeignKey(Comment))

api.py(Tastypie Resources)

class CommentResource(MongoResource):    
    class Meta:
        object_class = Comment
        queryset = Comment.objects.all()
        resource_name = 'comment'
        authentication = Authentication()
        authorization = Authorization()

class PostResource(MongoResource):
    commentList = ListField(models.ForeignKey('CommentResource', 'commentList')   #Wrong but just the expression of my incomprehension.
    class Meta:
        object_class = Post
        queryset = Post.objects.all()
        resource_name = 'post'
        authentication = Authentication()
        authorization = Authorization()

在此示例中,字段“commentList”包含引用“Comment”对象的“Object ID”列表。如果没有做任何事情,我的“发布”资源上的HTTP GET将给我:

[...],
objects: [
{
id: "4f47b159c789550388000000",
name: "Hello World",
commentList: "[u'4f47b14ec789550387000000']",
resource_uri: "/api/v1/post/4f47b159c789550388000000/"
}
]

我希望得到的是:

[...],
objects: [
{
id: "4f47b159c789550388000000",
name: "Hello World",
commentList: 
[
    comment:{
        title : "My comment title",
        body : "It would be great if tastypie-nonrel could do this!",
        resource_uri: "/api/v1/comment/454f4v59c789550388051486/"
    }
],
resource_uri: "/api/v1/post/4f47b159c789550388000000/"
}
]

我的问题是:如何解析对象评论的引用,并通过对资源发布的API调用使其可用?

如果无法做到这一点,那么设计我的非关系数据模型的最佳方式是什么,以便帖子可以包含多个评论,但 >评论可以单独访问并独立更新吗?

非常感谢你的帮助!!

1 个答案:

答案 0 :(得分:1)

尝试自定义PostResource的脱水功能,如下所示:

class PostResource(MongoResource):
    commentList = ListField(models.ForeignKey('CommentResource', 'commentList')
    class Meta:
        object_class = Post
        queryset = Post.objects.all()
        resource_name = 'post'
        authentication = Authentication()
        authorization = Authorization()

    def dehydrate(self, bundle):
        cmt_res = CommentResource()
        cmt_bundles = [cmt_res.build_bundle(c) for c in bundle.obj.commentList]
        for cb in cmt_bundles:
            cmt_res.full_dehydrate(cb)
        bundle.data['commentList'] = cmb_bundles