gpt4 book ai didi

Django,mongodb,Tastypie-nonrel : List of ForeignKey

转载 作者:可可西里 更新时间:2023-11-01 09:53:12 26 4
gpt4 key购买 nike

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

模型.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”包含引用“评论”对象的“对象 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/"
}
]

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

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

非常感谢您的帮助!

最佳答案

尝试像这样自定义 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

关于Django,mongodb,Tastypie-nonrel : List of ForeignKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9434823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com