我有一个带有“地址一对多”字段的Django“客户”模型。我想模拟地址模型,并将模拟模型分配到购物篮模型,然后将其保存到测试数据库。我目前正在使用类似:
address_mock = Mock(spec=Address)
address_mock._state = Mock()
customer = Customer(address=address_mock)
customer.save()
但是得到错误:
ValueError: Cannot assign "\<Mock spec='Address' id='72369632'\>": the current database router prevents this relation
我只是误解了模拟/测试数据库的工作原理?我不想为所有测试创建地址模型,并且该字段不可为空
使用它查看https://factoryboy.readthedocs.io/en/latest/orms.html,您可以定义子工厂,如下所示:
import factory
from faker import Factory
from address.models import Address
from customer.models import Customer
fake = Factory.create()
class AddressFactory(factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.LazyAttribute(lambda _: fake.street_address())
zip_code = factory.LazyAttribute(lambda _: fake.postcode())
place = factory.LazyAttribute(lambda _: fake.city())
class CustomerFactory(factory.DjangoModelFactory):
class Meta:
model = Customer
address = factory.SubFactory(AddressFactory)
phone = factory.LazyAttribute(lambda _: fake.phone_number())
CustomerFactory() #this creates a customer with a address
# or you can do this
address = AddressFactory()
customer.address = address
customer.save()
# or that way
c = CustomerFactory(address=address)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句