from mongoengine import *
SIZE = (('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
('XL', 'Extra Large'),
('XXL', 'Extra Extra Large'))
#连接数据库
connect('test')
class User(Document):
name = StringField(required=False,unique=False)
class Page(Document):
content = StringField(db_field="keyname",name="mongoengine name",default="default content")
#一对一
#author = ReferenceField(User)
answers = DictField()
values = ListField(IntField(), default=list)
size = StringField(max_length=3, choices=SIZE)
#一对多
authors = ListField(ReferenceField(User))
def to_dict(self):
page = {}
page['content'] = str(self.content)
page['answers'] = self.answers
page['values'] = self.values
page['size'] = self.size
page['authors'] = self.authors
return page
class Employee(Document):
name = StringField()
boss = ReferenceField('self')
profile_page = ReferenceField('ProfilePage')
class ProfilePage(Document):
content = StringField()
'''
john = User(name="John Smith")
john.save()
#john.drop_collection()
post = Page(content="Test Page")
post.answers={"p":"j"}
#一对一
post.author = john
post.values=[1,2]
post.size="S"
post.save()
#post.delete()
#post.drop_collection()
#一对多
bob = User(name="Bob Jones").save()
john = User(name="John Smith").save()
Page(content="Test Page", authors=[bob, john]).save()
Page(content="Another Page", authors=[john]).save() '''
#定义数据库别名和数据库名字
register_connection('book-db',"book")
register_connection('users-books-db',"author")
#保存到对应别名的数据库
class Book(Document):
name = StringField()
meta = {"db_alias": "book-db"}
class AcBook(Document):
name = StringField()
meta = {"db_alias": "book-db"}
class AuthorBooks(Document):
book = ReferenceField(Book)
meta = {"db_alias": "users-books-db"}
john = Book(name="John Smith")
john.save()
john1 = AcBook(name="John Smith")
john1.save()
john1.drop_collection()
post = AuthorBooks(book=john)
post.save()