gpt4 book ai didi

python - 为什么django的 `apps.get_model()`返回一个 `__fake__.MyModel`的对象

转载 作者:行者123 更新时间:2023-12-03 23:46:31 32 4
gpt4 key购买 nike

我正在编写自定义 Django 迁移脚本。根据 django docs on custom migrations ,我应该可以使用我的模型对比 apps.get_model() .但是,在尝试执行此操作时,出现以下错误:

AttributeError: type object 'MyModel' has no attribute 'objects'

我认为这与应用程序注册表未准备好有关,但我不确定。

示例代码:
def do_thing(apps, schema_editor):
my_model = apps.get_model('app', 'MyModel')

objects_ = my_model.objects.filter(
some_field__isnull=True).prefetch_related(
'some_field__some_other_field') # exc raised here


class Migration(migrations.Migration):

atomic = False

dependencies = [
('app', '00xx_auto_xxx')
]

operations = [
migrations.RunPython(do_thing),
]
apps.get_model() 的简单打印语句的返回值显示如下: <class '__fake__.MyModel'> .我不确定这是什么,是否是没有准备好的结果。

编辑:

我找不到任何资源来解释为什么我会收到 __fake__对象,所以我决定修改代码。我通过抢占来让它工作 apps从 args 中可以看出:
def do_thing(apps, schema_editor):
from django.apps import apps

my_model = apps.get_model('app', 'MyModel')

objects_ = my_model.objects.filter(
some_field__isnull=True).prefetch_related(
'some_field__some_other_field') # no more exc raised here

我仍然很困惑,任何帮助将不胜感激。

最佳答案

假货是历史模型。这是来自 Django docs 的解释:

When you run migrations, Django is working from historical versions of your models stored in the migration files.

[...]

Because it’s impossible to serialize arbitrary Python code, these historical models will not have any custom methods that you have defined. They will, however, have the same fields, relationships, managers (limited to those with use_in_migrations = True) and Meta options (also versioned, so they may be different from your current ones).


万一 objects是自定义管理器,可以设置 use_in_migrations = True使其在迁移中可用。

关于python - 为什么django的 `apps.get_model()`返回一个 `__fake__.MyModel`的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62418465/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com