具有默认值的字段中的 Django factory boy post_generation 不起作用

Django factory boy post_generation in field with default value don't work

我有一个模型,其字段为 int 类型,该字段具有默认值

我正在尝试使用 post_generation 在该字段中设置一个值,但没有任何反应,该字段保持默认值,当我尝试使用 .set 时出现以下错误:

AttributeError: 'int' object has no attribute 'set'

这是我要填充的字段

@factory.post_generation
def priority(obj, create, extracted, **kwargs):
    for series in range(obj.patrimony.count()): # this is a sequence of numbers
        series += 1
        obj.priority.set(series)

这是模型,只是一个简单的模型

class Series(models.Model):
    priority = models.IntegerField(_("Priority"), default=0, null=True)

谁能帮我开开眼?

您遇到了两个问题:

设置字段值

Series.priority 始终是 int,整数没有 .set() 方法(它们是不可变对象)。 您应该使用 obj.priority = series

进行设置

适时设定值

factory_boy 通过 3 个步骤创建对象: 1. 评估所有预声明(LazyAttributeSequence等); 2.在数据库中创建对象(调用Series.objects.create(...)) 3. 评估post-generation declarations

如果 obj.patrimony 创建 系列之前已知,您可以简单地拥有:

class SeriesFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Series
    priority = factory.LazyAttribute(lambda o: o.patrimony.count())

(我也调整了声明,因为你的 for series in ... 循环严格等同于 obj.priority = obj.patrimony.count()