MongoEngine ValidationE公司

2024-05-14 23:41:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须创建一个数据库,以及如何检查是否所有条目都输入到数据库中,是否使用pythonshell。在

我写了一个叫做审判的课程

class Trial(db.Document):
    project_name = db.StringField(max_length=255,required=True)
    list_of_materials = db.ListField(db.EmbeddedDocumentField('List_Of_Materials'))
    abstract = db.StringField(max_length=255,required=True)
    vehicle = db.StringField(max_length=255,required=False)
    responsibilities = db.ListField(db.EmbeddedDocumentField('Responsibilities')) 

我将材料和职责分类如下:

^{pr2}$

现在我使用pythonshell在数据库中创建一个条目。在

trial_test = Trial(project_name = 'nio field trip management',
                list_of_materials = [List_Of_Materials(mat_name = 'Laptop')],
                abstract = 'All is well that ends well',
                vehicle = Vehicle(veh_name='My Laptop',veh_num='GA07EX1234'),
                responsibilities = [Responsibilities(employee='Prashant',objective='Setup the Website')],

我得到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 12, in <module>
  File "C:\Anaconda\lib\site-packages\mongoengine\base\document.py", line 85, in __init__
    value = field.to_python(value)
  File "C:\Anaconda\lib\site-packages\mongoengine\base\fields.py", line 261, in to_python
    self.error('You can only reference documents once they'
  File "C:\Anaconda\lib\site-packages\mongoengine\base\fields.py", line 124, in error
raise ValidationError(message, errors=errors, field_name=field_name)
mongoengine.errors.ValidationError: You can only reference documents once they have been saved to the database

代码的第12行是responsibilities=db.ListField(db.EmbeddedDocumentField('Responsibilities'))

从上面的错误我可以理解为,我们可以先进入“责任”和“材料清单”,但“材料清单”中的条目没有显示任何错误,而“责任”中的条目显示了上述错误。在

我能做些什么来避免这个问题?在


Tags: namein数据库fielddb错误linerequired
1条回答
网友
1楼 · 发布于 2024-05-14 23:41:23

您确定您发送的Trial模型是正确的吗?在

当您在文档中声明了一个ReferenceField,并且您在保存被引用的文档之前尝试保存此文档时,会引发此ValidationError(Mongoengine将MongoDB中的引用字段表示为包含引用的类和ObjectId的dictionnay)。在

EmbeddedDocumentField不是{}。它们与主文档的保存时间相同。因此,我不认为您的错误来自list_of_materials或{}属性。如果在示例中删除了车辆分配,则此代码可以完美地工作。在

根据您的代码示例,我猜有一个类

class Vehicle(db.Document):
    veh_name = db.StringField()
    veh_num = db.StringField()

你的模型是:

^{pr2}$

然后,你的例子应该是:

trial_test = Trial(
     project_name = 'nio field trip management',
     list_of_materials = [List_Of_Materials(mat_name = 'Laptop')],
     abstract = 'All is well that ends well',
     vehicle = Vehicle(veh_name='My Laptop',veh_num='GA07EX1234'),
     responsibilities = [Responsibilities(employee='Prashant',objective='Setup the Website')]
)
trial_test.vehicle.save()  # Saving the reference BEFORE saving the trial.
trial_test.save()

相关问题 更多 >

    热门问题