class User(Document): __collection__ = 'users' index = IntField(required=True) email = StringField(required=True) first_name = StringField( db_field="whatever", max_length=50, default=lambda: "Bernardo" ) last_name = StringField(max_length=50, default="Heynemann") is_admin = BooleanField(default=True) website = URLField(default="http://google.com/") updated_at = DateTimeField( required=True, auto_now_on_insert=True, auto_now_on_update=True ) embedded = EmbeddedDocumentField( EmbeddedDocument, db_field="embedded_document" ) nullable = EmbeddedDocumentField( EmbeddedDocument, db_field="nullable_embedded_document" ) numbers = ListField(IntField()) posts = ListField(ReferenceField(reference_document_type=Post)) def __repr__(self): return "%s %s <%s>" % (self.first_name, self.last_name, self.email)
class Alteration(BaseDocument): title = StringField(max_length=64) product = StringField(max_length=32) execute_at = DateTimeField() reason = StringField(max_length=128) effect = StringField(max_length=128) sent_at = DateTimeField() sent_by = ListField(StringField()) sent_to = ListField(JsonField())
class Post(Document): __collection__ = 'posts' title = StringField(required=True) text = StringField(required=True, db_field='content') category = ReferenceField(reference_document_type=Category) comments = ListField(EmbeddedDocumentField(embedded_document_type=Comment))
class Event(BaseDocument): name = StringField(required=True, max_length=255) status = StringField(required=True, max_length=16) level = StringField(required=True, max_length=16) started_at = DateTimeField(required=True) ended_at = DateTimeField(required=True) # created_by = ReferenceField(reference_document_type=User) created_at = DateTimeField(required=True, auto_now_on_insert=True) participants = ListField(JsonField(required=True))
def test_base_field_must_be_a_field(self): try: ListField("invalid", db_field="test") except ValueError: err = sys.exc_info()[1] expect(err) \ .to_have_an_error_message_of("The list field 'field' argument must be an instance of BaseField, not 'invalid'.") else: assert False, "Should not have gotten this far"
class Message(BaseDocument): # 消息内容 title = StringField(max_length=64) content = StringField(max_length=500) comment = StringField(max_length=200) # 发送信息 sent_from = JsonField() sent_at = DateTimeField() sent_by = ListField(StringField()) sent_to = ListField(JsonField()) next_sent_at = DateTimeField() # 管理信息 created_at = DateTimeField(auto_now_on_insert=True) # created_by = ReferenceField() updated_at = DateTimeField(auto_now_on_insert=True, auto_now_on_update=True) status = StringField(max_length=32, default=MessageStatusEnum('未发送').name) configure = JsonField() log = ListField(JsonField()) is_active = BooleanField(default=True) @classmethod def validate_values(cls, dic, allow_cover=True): validated = super(Message, cls).validate_values(dic, allow_cover) schedule = validated['configure'].get('schedule', DefaultMessageSchedule) customized = validated['configure'].get('customized', []) if schedule == 'once': pass elif schedule == 'customized' and customized: sent_at = validated.get('sent_at') validated['next_sent_at'] = get_next_day(sent_at, customized, schedule) else: sent_at = validated.get('sent_at') validated['next_sent_at'] = get_next_day(sent_at, 1, schedule) return validated @staticmethod async def ir_cron(): with open('/tmp/wodeshijie', 'a+') as f: for m in await Message.objects.find_all(): f.write('%s \n' % m.title) return True
class Lesson(Document): id = IntField() name = StringField(required=True) audience = StringField() teacher_name = StringField() lesson_type = StringField() start_time = StringField() color = StringField() comments = ListField(EmbeddedDocumentField(embedded_document_type=Comment)) day = ReferenceField('DayTimetable')
class User(Document): __collection__ = "AggregationUser" email = StringField(required=True) first_name = StringField(max_length=50, default=lambda: "Bernardo") last_name = StringField(max_length=50, default="Heynemann") is_admin = BooleanField(default=True) updated_at = DateTimeField(required=True, auto_now_on_insert=True, auto_now_on_update=True) number_of_documents = IntField() list_items = ListField(IntField())
def test_to_query(self): field = ListField(StringField()) field.from_son(["1", "2", "3"]) expect(field.to_query(["1", "2", "3"])).to_equal({ "$all": ["1", "2", "3"] }) expect(field.to_query("string")).to_equal("string")
class BoardDocument(BaseDocument): """Доска на которой размещены списки с карточками. Доска может быть доступна для нескольких пользователей. :type title: str Заголовок доски; :type listsCards: list Набор списков карточек для конкретной доски; :type users: list Список пользователей имеющий доступ к доске; """ __collection__ = "board" title = StringField(required=True) users = ListField(ReferenceField(UserDocument)) def check_permission(self, document_user: UserDocument): """Проверка прав доступа к текущему документу у определенного пользователя.""" return document_user._id in self.users
class ThirdPartyPlatform(BaseDocument): """ authentication: [{ 'type': 'text', 'label': '账户', 'name': 'account', 'required': true }, { 'type': text, 'label':'密码', 'name': 'password', 'required': true }] """ name = StringField(max_length=32) code = StringField(max_length=32) authentication = ListField(JsonField())
def test_create_list_field(self): field = ListField(StringField(), db_field="test") expect(field.db_field).to_equal("test") expect(field._base_field).to_be_instance_of(StringField)
class SizeDocument(Document): items = ListField(IntField()) item_size = IntField(default=0, on_save=lambda doc, creating: len(doc.items))
class Post(Document): title = StringField(required=True) body = StringField(required=True) comments = ListField(EmbeddedDocumentField(Comment))
class ElemMatchDocument(Document): items = ListField(IntField())
def test_validate_propagates(self): field = ListField(StringField()) expect(field.validate(["1", "2", "3"])).to_be_true() expect(field.validate(["1", 2, "3"])).to_be_false()
class Group(Document): id = IntField() name = StringField(required=True) users = ListField(ReferenceField('User')) university = ReferenceField('University') timetable = EmbeddedDocumentField(Schedule())
def test_is_empty(self): field = ListField(StringField()) expect(field.is_empty(None)).to_be_true() expect(field.is_empty([])).to_be_true() expect(field.is_empty("some")).to_be_false()
def test_item_embedded_type(self): class OtherType(Document): pass field = ListField(EmbeddedDocumentField(OtherType)) expect(field.item_type).to_equal(OtherType)
def test_item_reference_type(self): class OtherType(Document): pass field = ListField(ReferenceField(OtherType)) expect(field.item_type).to_equal(OtherType)
def test_embedded_type(self): field = ListField(StringField()) expect(field.item_type).to_equal(StringField)
def test_validate_none(self): field = ListField(StringField()) expect(field.validate(None)).to_be_true() field = ListField(StringField(), required=True) expect(field.validate(None)).to_be_false()
class DayTimetable(Document): name = StringField(required=True) lessons = ListField(EmbeddedDocumentField(Lesson())) schedule = ReferenceField('scheduler.model.Schedule')
class ElemMatchEmbeddedParentDocument(Document): items = ListField(EmbeddedDocumentField(ElemMatchEmbeddedDocument))
class Schedule(Document): days = ListField(EmbeddedDocumentField(DayTimetable())) user = ReferenceField(reference_document_type=User) group = ReferenceField('scheduler.model.Group') pass
class RawQueryDocument(Document): items = ListField(EmbeddedDocumentField(RawQueryEmbeddedDocument))
class University(Document): id = IntField() name = StringField(required=True) groups = ListField(EmbeddedDocumentField(Group()))
class Base(Document): __collection__ = 'base' __lazy__ = False list_val = ListField(ReferenceField(reference_document_type=Ref))
class User(Document): name = EmbeddedDocumentField(embedded_document_type=Name) email = StringField(db_field='email_address') numbers = ListField(base_field=IntField())
def test_from_son(self): field = ListField(StringField()) expect(field.from_son([])).to_equal([]) expect(field.from_son(None)).to_equal([]) expect(field.from_son(["1", "2", "3"])).to_equal(["1", "2", "3"])