将现有数据库手动迁移到 MongoEngine 不会填充字段

问题描述 投票:0回答:1

我有一个现有的数据数据库,我想将其与 MongoEngine 一起使用。我更新了课程如下:

class World(Document):
    user = ReferenceAttr(choices=["User"], required=True)
    journal = ReferenceAttr(choices=[Journal])
    name = StringAttr()
    history = StringAttr()
    last_updated = DateTimeField(default=datetime.now)

我手动调整数据库条目以适应 MongoEngine 的架构。下面是数据库中手动迁移结果的示例:

    _id: ObjectId('65ac20ed012362b1d87ce645'),
    _cls: 'World',
    name: 'Red Sun',
    history: '',
    journal: {
        _cls: 'Journal',
        _ref: DBRef('journal', '65ba6fbe37d921ede3686388')
    },
    user: {
        _cls: 'User',
        _ref: DBRef('user', '65ac20e3012362b1d87ce63f')
    },
    last_updated: ISODate('2024-08-19T14:34:56.874Z')

当我这样做时

print(cls.objects.all())
,我为每个条目获得一个对象,到目前为止似乎是正确的:

[<World: World object>, <World: World object>, <World: World object>, <World: World object>, <World: World object>, <World: World object>, <World: World object>, <World: World object>]

但是,打印

[vars(o) for o in cls.objects.all()]
会导致
{}
s。

当我尝试访问对象属性(例如

obj.name
)时,我得到:

   instance = <World: World object>, owner = <class 'models.world.World'>

    def __get__(self, instance, owner):
        """Descriptor for retrieving a value from a field in a document."""
        if instance is None:
            # Document class being used rather than a document object
            return self
    
        # Get value from document instance if available
>       return instance._data.get(self.name)
E       AttributeError: 'World' object has no attribute '_data'. Did you mean: '_delta'?

我已经追踪了代码,但无法弄清楚为什么它没有填充值。大家有什么想法吗?

据我所知,所有 Document 对象都应该有一个默认的 _data 属性,所以我不知道为什么该对象中没有任何内容。

python mongodb mongoengine
1个回答
0
投票

你为什么使用

ReferenceAttr
? 请使用世界级的ReferenceField

from mongoengine import *
from datetime import datetime

class World(Document):
    user = ReferenceField('User', required=True)  #  You can use it like this, but because I don't have the user class, I wrote it as a string ReferenceField(User, required=True) 
    journal = ReferenceField('Journal')
    name = StringField()
    history = StringField()
    last_updated = DateTimeField(default=datetime.now)

用法示例:

world = World.objects.first()
print(world.name)
© www.soinside.com 2019 - 2024. All rights reserved.