你能为工厂男孩重写一个模型函数吗?

2024-06-16 08:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我用工厂男孩做模特。另一个模型有一个外键,该模型的第一个obj用于模型的字符串表示。示例结构:

class A(models.Model):
    ...

    def __str__(self):
    return self.reverseForeignKey_set.first().name

class AFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = models.A

    some_attribute = factory.RelatedFactory(
        ReverseModelFactory,
        'a',
        )

但是当我用factory_boy来创建时,它会给我一个错误:

^{pr2}$

有什么我能做的吗?比如只为工厂男孩在模型A上重写str方法?在


Tags: 字符串模型selfobj示例modelmodelsfactory
1条回答
网友
1楼 · 发布于 2024-06-16 08:33:22

您遇到这样的问题是因为A模型实例的创建时间早于ReverseModel实例。在

正如工厂男孩的文件所说:

RelatedFactory: this builds or creates a given factory after building/creating the first Factory.

http://factoryboy.readthedocs.io/en/latest/reference.html#post-generation-hooks

首先,您应该创建ReverseModel,然后创建A模型实例。 正如工厂男孩文件中所说:

When one attribute is actually a complex field (e.g a ForeignKey to another Model), use the SubFactory declaration

因此,您可以为FK模型定义工厂,并将其定义为工厂中的子工厂。在

# models.py
class A(models.Model):
    ...

    def __str__(self):
        return self.reverseForeignKey_set.first().name

# factories.py
import factory
from . import models

class ReverseModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.ReverseModel

        # Define your model fields
        attr = factory.Faker('text', max_nb_chars=255)

class AFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.A

    some_attribute = factory.SubFactory(ReverseModelFactory)

在这种情况下,将首先创建ReverseModelFactory对象,该对象应该可以解决您的问题。 有关详细信息,请参见http://factoryboy.readthedocs.io/en/latest/recipes.html。在

我还需要注意的是,如果你想处理很多字段,你应该使用后生成钩子:

^{pr2}$

有关详细信息,请参见http://factoryboy.readthedocs.io/en/latest/recipes.html#simple-many-to-many-relationship。在

相关问题 更多 >