简体   繁体   English

如何在 django 中模拟 model 的外键模型?

[英]How to mock foreign key models of a model in django?

I have a django 'Customer' model with an Address one-to-many field.我有一个带有一对多地址字段的 django 'Customer' model。 I want to mock the address model, and assign the mock to the basket model and save that to the test database.我想模拟地址 model,并将模拟分配给篮子 model 并将其保存到测试数据库。 I am currently using something like:我目前正在使用类似的东西:

address_mock = Mock(spec=Address)
address_mock._state = Mock()
customer = Customer(address=address_mock)
customer.save()

but get the error:但得到错误:

ValueError: Cannot assign "\<Mock spec='Address' id='72369632'\>": the current database router prevents this relation

am I just misunderstanding how mock/the test db works?我只是误解了模拟/测试数据库的工作原理吗? I don't want to have to create an address model for all my tests, and the field is not nullable我不想为我的所有测试创建地址 model,并且该字段不可为空

Check out https://factoryboy.readthedocs.io/en/latest/orms.html with it you can define sub factories like so:查看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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM