如何为mongoengine Document制作类属性和实例属性之间的区别?

时间:2016-01-28 20:41:10

标签: python python-2.7 mongoengine flask-mongoengine

如何为扩展mongoengine Document的类创建类属性和实例属性之间的区别?所有属性看起来都像是类属性,但在创建两个实例时,这些变量不会被共享。 如何使用mongoengine创建类属性和实例属性?

------编辑------

class User(Document):
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)

这是mongoengine文档提供的用于定义用户文档的示例。 这些定义的方式,它们是类级属性。但是,Document.py和BaseDocument.py注意不要在User的实例之间共享这些内容。 我希望在实例之间共享类级别属性,并且在文档上调用save()方法时也保存到mongodb

1 个答案:

答案 0 :(得分:1)

如果您创建两个User实例并保存它们,那么您将在集合中有两个文档。如果您希望他们两者都有共同的信息,那么实现这一目标的方法很少:

<强> 1。默认属性

class User(db.Document):
    email = db.StringField(required=True)
    first_name = db.StringField(max_length=50)
    last_name = db.StringField(max_length=50)
    usertype = db.StringField(default="web user")


u1 = User(email="u1@example.com", first_name="user", last_name="one").save()
u2 = User(email="u2@example.com", first_name="user", last_name="two").save()

assert u1.usertype == "web user"
assert u2.usertype == "web user"

<强> 2。嵌入式文件

class UserType(db.EmbeddedDocument):
    role = db.StringField(choices=['Admin','Basic','Guest'])

class User(db.Document):
    email = db.StringField(required=True)
    first_name = db.StringField(max_length=50)
    last_name = db.StringField(max_length=50)
    usertype = db.EmbeddedDocumentField(UserType)


basic = UserType(role="Basic")
u1 = User(email="u1@example.com", first_name="user", last_name="one", usertype=basic).save()
u2 = User(email="u2@example.com", first_name="user", last_name="two", usertype=basic).save()

assert u1.usertype.role == "Basic"
assert u2.usertype.role == "Basic"

第3。参考文件

class UserType(db.Document):
    role = db.StringField(choices=['Admin','Basic','Guest'])

class User(db.Document):
    email = db.StringField(required=True)
    first_name = db.StringField(max_length=50)
    last_name = db.StringField(max_length=50)
    usertype = db.ReferenceField(UserType)


basic = UserType(role="Basic").save()
u1 = User(email="u1@example.com", first_name="user", last_name="one", usertype=basic).save()
u2 = User(email="u2@example.com", first_name="user", last_name="two", usertype=basic).save()

assert u1.usertype.role == "Basic"
assert u2.usertype.role == "Basic"

何时使用EmbeddedDocumentReferenceField取决于on your data model design