使用`django_get_or_create`与一对一相关字段

jfewjypa  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(73)

鉴于这个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,因为大多数时候我只需要一个用户,我为特定的情况创建特定的类(UserIsStaffFactoryUserSuperAdminFactory
我从www.example.com复制了RelatedFactory/SubFactoryhttps://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
gab6jxml

gab6jxml1#

我是这样解决这个问题的:

import factory
class UserFactory(factory.django.DjangoModelFactory):
    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()}@fakecompany.com")
    customer = factory.RelatedFactory(CustomerFactory, factory_related_name="user", user=None)
    is_staff = False

    class Meta:
        model = User
        django_get_or_create = ('username',)

class CustomerFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = "customers.Customer"
        django_get_or_create = ("user",)
    user = factory.SubFactory('private.tests.fixtures.UserFactory')

看起来很简单😅

相关问题