我正在尝试使用 factory_boy 测试两个 Django 模型之间的多对多关系。factory_boy 文档似乎没有讨论这个问题,我无法弄清楚我做错了什么。当我运行第一个测试时,我收到错误“AttributeError: 'Pizza' object has no attribute 'topping'”。我在第二次测试中遇到了类似的错误。
当我在调试器中运行测试时,我可以看到一个“toppings”对象,但它不明白如何从中获取名称。我是否正确定义了 PizzaFactory 的 _prepare 方法?当您具有多对多关系时,如何从另一个表访问一个表中的名称?
谢谢。
模型.py:
from django.db import models
class Topping(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Pizza(models.Model):
name = models.CharField(max_length=100)
toppings = models.ManyToManyField(Topping)
def __unicode__(self):
return self.name
工厂.py:
import factory
from models import Topping, Pizza
class ToppingFactory(factory.Factory):
name = 'mushrooms'
class PizzaFactory(factory.Factory):
name = 'Vegetarian'
@classmethod
def _prepare(cls, create, **kwargs):
topping = ToppingFactory()
pizza = super(PizzaFactory, cls)._prepare(create, **kwargs)
pizza.toppings.add(topping)
return pizza
测试.py
from django.test import TestCase
import factory
from app.models import Topping, Pizza
from app.factories import ToppingFactory, PizzaFactory
class FactoryTestCase(TestCase):
def test_pizza_has_mushrooms(self):
pizza = PizzaFactory()
self.assertTrue(pizza.topping.name, 'mushrooms')
def test_mushrooms_on_pizza(self):
topping = ToppingFactory()
self.assertTrue(topping.pizza.name, 'Vegetarian')