我想用 Model Bakery 创建一个 Person 实例。我的 Person 模型如下所示:
User = get_user_model()
class Person(models.Model):
user = models.OneToOneField(User, related_name="friend", on_delete=CASCADE)
country = models.CharField(max_length=100)
我的 baker_recipes.py 看起来像这样:
from model_bakery.recipe import Recipe
User = get_user_model()
test_user = User(username="test_user")
person = Recipe(Person, user = test_user)
我的 tests.py 看起来像这样:
import pytest
from model_bakery import baker
@pytest.mark.django_db()
class TestPerson:
def setup(self):
self.person = baker.make_recipe("company.tests.person")
def test_country_access(self):
assert True
但是,当我使用此设置运行 pytest 时,出现以下错误:
django.db.utils.IntegrityError: insert or update on table "company_person" violates foreign key constraint "company_person_user_id_4f1cc5d0_fk_auth_user_id"
DETAIL: Key (user_id)=(411) is not present in table "auth_user".