gpt4 book ai didi

Django 抽象模型 + DB 迁移 : tests throw "cannot ALTER TABLE because it has pending trigger events"

转载 作者:行者123 更新时间:2023-12-04 08:54:00 25 4
gpt4 key购买 nike

我想编写一个抽象模型 mixin,我可以用它来创建 OneToOne - 与用户模型的关系。这是我的代码:

from django.conf import settings
from django.db import models


class Userable(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)

class Meta:
abstract = True

我为此模型编写了以下测试:
class TestUserable(TestCase):

mixin = Userable

def setUp(self):
user = User.objects.create_user(
email="testuser@test.com",
name="Test User",
password="test1234test"
)
self.user = user
self.model = ModelBase(
'__TestModel__' + self.mixin.__name__, (self.mixin,),
{'__module__': self.mixin.__module__}
)

with connection.schema_editor() as schema_editor:
schema_editor.create_model(self.model)

def test_user(self):
self.model.objects.create(user=self.user)
self.assertEqual(self.model.objects.count(), 1)

def tearDown(self):
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(self.model)

我的问题是,这个测试是 tearDown()方法抛出以下错误:
django.db.utils.OperationalError: cannot DROP TABLE "core___testmodel__userable" because it has pending trigger events

这可能是什么原因?我确实跑了 python manage.py makemigrationspython manage.py migrate ,但没有挂起的迁移(正如预期的那样,因为这是一个抽象模型)。

编辑:它似乎与 OneToOneFields 或 ForeignKeys(关系)有关。如果我将此代码更改为常规字段,如 CharFields 或 IntegerFields,它会起作用。

EDIT2:如果您有另一种更好的方法来测试使用外键的抽象基本模型,请告诉我!

最佳答案

测试抽象模型的常见做法是为测试创建实际模型

这是 model-utils 中的示例项目https://github.com/jazzband/django-model-utils/blob/master/tests/test_models/test_timestamped_model.py

from tests.models import UserableTest

class TestUserable(TestCase):
def setUp(self):
user = User.objects.create_user(
email="testuser@test.com",
name="Test User",
password="test1234test"
)
self.user = user

def test_user(self):
UserableTest.objects.create(user=self.user)
self.assertEqual(UserableTest.objects.count(), 1)

在这个项目中,他们有单独的设置 DJANGO_SETTINGS_MODULE = tests.settings https://github.com/jazzband/django-model-utils/blob/master/tests/settings.py
INSTALLED_APPS = (
'model_utils',
'tests',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3'
}
}
SECRET_KEY = 'dummy'

模型在 https://github.com/jazzband/django-model-utils/blob/master/tests/models.py 中描述
from myapp.models import Userable

class UserableTest(Userable):
pass

关于Django 抽象模型 + DB 迁移 : tests throw "cannot ALTER TABLE because it has pending trigger events",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50553037/

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