3

On my Django-mongodb model, I would like to have an object with a listField containing reference to other objects. Here is an example of what I want to achieve :

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

In this example, the field "commentList" contains a list of "Object ID" referencing "Comment" objects. If nothing is done, an HTTP GET on my "Post" resource will give me:

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

What I would love to get is this :

[...],
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/"
}
]

My question is : How can I resolve the reference to objects Comment and make it available with a API call to the ressource Post?

If this is not possible, what would be the best way to design my non-relational data model so that a Post can contain multiple Comment, but that Comment can alo be accessed on its own and updated independently?

Thanks a lot for your help!!

4

1 回答 1

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
于 2012-07-21T08:55:14.790 回答