【发布时间】:2013-03-26 09:43:47
【问题描述】:
我有一个相当重的User 文档类,我想将它分成两部分:UserProfile 文档中的用户个人资料(姓名和头像)和User 文档中的其余部分,例如这个(使用 MongoEngine):
from mongoengine import *
class User(Document):
login = StringField()
password = StringField()
posts = ListField(ReferenceField("Post", dbref = False))
#... a bunch of other fields
class UserProfile(Document):
name = StringField()
avatar = URLField()
我想为 UserProfile 和 User 使用相同的 ObjectId,这样我只需要一个 ObjectId 来引用 User 和 UserProfile。毕竟,这实际上是一对一的关系,而且由于用户可以撰写许多帖子,我不想将她的个人资料嵌入帖子本身。创建用户文档时,我会立即创建相应的配置文件,如下所示:
john = User.objects.create(login = "john", password = "super!password")
john_profile = UserProfile.objects.create(id = john.id, name = "John Smith",
avatar = "http://www.example.com/img/photo.jpg")
到目前为止一切顺利。现在我有一个Post 文档,其中有一个引用User 文档的author 字段:
class Post(Document):
author = ReferenceField("User", dbref = False)
text = StringField()
我想添加一个基于相同 ObjectId 的 author_profile 引用。我试过这个:
class Post(Document):
author = ReferenceField("User", dbref = False)
author_profile = ReferenceField("User", db_field = "author", dbref = False)
text = StringField()
但我得到以下异常:
mongoengine.base.InvalidDocumentError: Multiple db_fields defined for: author
所以看来我必须“手动”这样做。可能是这样的:
class Post(Document):
author = ReferenceField("User", dbref = False)
text = StringField()
@property
def author_profile(self):
if hasattr(self, "_author_profile"):
return self._author_profile
self._author_profile = UserProfile.objects.get(id = self._data["author"].id)
return self._author_profile
我想这还不错,但没有更好的解决方案吗?
谢谢。
注意:我阅读了关于一对一关系的 mongodb documentation 以及 mongoengine ReferenceField documentation,但它对这个特定问题没有帮助。
【问题讨论】:
-
为什么不使用登录名(我想它是唯一的)作为_id?
-
是的,我可以,你是对的,但我认为它不能解决我的问题:我将如何实现
post.author和post.author_profile?我需要两个 ReferenceField,一个指向 User,另一个指向 UserProfile,两者都具有相同的 id(无论是 objectid 还是登录名)。你明白我的意思了吗? -
我从来没有使用过 mongoengine,所以很遗憾我无法帮助你。另外,我不喜欢使用 DBRef,因为我更喜欢手动控制关系。我不知道您是否是 mongodb 新手,但要记住的重要一件事是不要像关系数据库那样设计数据。
标签: mongodb one-to-one mongoengine