2012-02-24 11 views
3

私のDjango-mongodbモデルでは、他のオブジェクトへの参照を含むlistFieldを持つオブジェクトが必要です。ここで私が達成したいものの一例である:Django、mongodb、Tastypie-nonrel:ForeignKeyのリスト

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参考)この例では

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呼び出しで利用できるようにする投稿?これが不可能な場合

は、何がポストは、複数のコメントを含めることができるように私の非リレーショナルデータモデルを設計するための最良の方法だろうが、それコメントはALO独自にアクセスすることができ、独立して更新?

ありがとうございました!

答えて

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 
関連する問題