如何在另一个集合 MongoEngine 中创建文档时引用集合中的现有文档

How to reference existing documents in collection on creation of documents in another collection MongoEngine

我使用的模型如下:


# Creating data models for the interns first project.
class Sex(db.Document):
    _id = ObjectIdField(required=True, default=ObjectId, unique=True, primary_key=True)
    gender = db.StringField()


class Address(db.EmbeddedDocument):
    _id = ObjectIdField(required=True, default=ObjectId, unique=True, primary_key=True)
    number = db.IntField()
    street = db.StringField()
    city = db.StringField()
    eircode = db.StringField()


class Person(db.Document):
    _id = ObjectIdField(required=True, default=ObjectId, unique=True, primary_key=True)
    name = db.StringField()
    sex = db.ReferenceField(Sex, required=True)
    address = db.ListField(db.EmbeddedDocumentField(Address))

我已经在 'sex' 集合中创建了作为文档的值,我想在 'person' 集合中插入新文档时引用其中一个值。 (据我所知,这将是一对多的关系)

这就是我得到的结果,但没有按预期工作:

    if Person(name='USERNAME', sex=Sex(_id='602a593d3149eb362c296561', gender='Male'),
              address=[Address(number=1, street='STREET 1', city='CITY 1', eircode='EIRCODE 1'),
                       Address(number=2, street='STREET 2', city='CITY 2', eircode='EIRCODE 2')]
              ).save():
        return 'Successfully added'
    return 'Error in Register'

发现我亲自在 oid (_id) 字段上设置默认值时出错,删除它后工作正常。

# Creating data models for the interns first project.
class Sex(db.Document):
    _id = ObjectIdField(required=True, default=ObjectId, unique=True, primary_key=True)
    gender = db.StringField()


class Address(db.EmbeddedDocument):
    _id = ObjectIdField(required=True, default=ObjectId, unique=True, primary_key=True)
    number = db.IntField()
    street = db.StringField()
    city = db.StringField()
    eircode = db.StringField()


class Person(db.Document):
    _id = ObjectIdField()
    name = db.StringField()
    sex = db.ReferenceField(Sex, required=True)
    address = db.ListField(db.EmbeddedDocumentField(Address))