鉴于这个django模型
from django.db import Model
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT)
some_other_field = model.CharField(...)
我为用户和客户模型创建了2个工厂:
import factory
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
django_get_or_create = ('username',)
first_name = factory.Faker("first_name", locale="fr_FR")
last_name = factory.Faker("last_name", locale="fr_FR")
username = factory.LazyAttribute(lambda m: f"{m.first_name[0]}{m.last_name[0]}".lower())
email = factory.LazyAttribute(lambda m: f"{m.first_name.lower()}.{m.last_name.lower()}@ielo.net")
customer = factory.RelatedFactory(CustomerFactory, factory_related_name="user", user=None)
is_staff = False
class CustomerFactory(factory.django.DjangoModelFactory):
class Meta:
model = "customers.Customer"
user = factory.SubFactory('myapp.tests.fixtures.UserFactory', customer=None)
为了避免不稳定的测试,我设置了django_get_or_create
,因为大多数时候我只需要一个用户,我为特定的情况创建特定的类(UserIsStaffFactory
,UserSuperAdminFactory
)
我从www.example.com复制了RelatedFactory/SubFactory
https://factoryboy.readthedocs.io/en/stable/recipes.html#example-django-s-profile,但如果我运行:
u1 = UserFactory(username='foo')
u2 = UserFactory(username='foo')
# raise IntegrityError, UNIQUE constraint failed: customers_customer.user_i
1条答案
按热度按时间gab6jxml1#
我是这样解决这个问题的:
看起来很简单😅