【问题标题】:One to One relationship in factory - Integrity Error工厂中的一对一关系 - 完整性错误
【发布时间】:2016-03-31 12:56:55
【问题描述】:

我正在使用 factory_boy 来创建我正在开发的应用程序的工厂。 我在尝试创建与另一个模型具有一对一关系的模型的工厂时遇到问题

以下是模型:

class Playlist(AccountDependantMixin, models.Model):
    test = models.OneToOneField('core.PlaylistTest', related_name='playlist')

class PlaylistTest(Test):
    pass

AccountDependantMixin 是一个包含额外信息的类。它在外面,因为其他模型也需要它。 我有不同类型的测试。这就是 PlaylistTest 为空的原因

这是工厂:

class PlaylistTestFactory(factory.DjangoModelFactory):
    class Meta:
        model = PlaylistTest


class PlaylistFactory(factory.DjangoModelFactory):
    class Meta:
        model = Playlist       
    test = factory.SubFactory(PlaylistTestFactory)

这是我尝试使用工厂初始化实例的方式:

self.playlist = PlaylistFactory(creator=AdminUserFactory(account=self.account))

我收到以下错误:

IntegrityError: null value in column "test_id" violates not-null constraint
DETAIL:  Failing row contains (1, , playlist0, sub_title0, description0, 0, t, f, 2016-03-31 12:49:23.739207+00, 0, 2, 1, null)

【问题讨论】:

  • 什么是 AccountDependantMixin?
  • @daniel 这是一个包含额外信息的类。它在外面,因为其他模特也需要它。
  • PlaylistTestFactory 中没有任何属性,也许这就是为什么没有创建相关对象而是设置为 null 的原因?
  • @v1k45 我在 PlaylistTest 中添加了一个字段,然后在工厂设置它,但它没有解决它
  • PlaylistTest中主键列的名称是什么?你能把它添加到你的 sn-p 中吗?

标签: python django testing factory factory-boy


【解决方案1】:

test = factory.RelatedFactory(PlaylistTestFactory)

您需要使用SubFactory 而不是RelatedFactory 以便它首先创建测试对象:

RelatedFactory 的行为主要类似于 SubFactory,主 之后生成相关工厂的区别 基础工厂。

https://factoryboy.readthedocs.org/en/latest/reference.html#factory.RelatedFactory

【讨论】:

    【解决方案2】:

    问题是我有另一个模型与另一个从 Test 继承的一对一到另一个类。

    我将子工厂添加到这个其他类的工厂中,问题就解决了。

    【讨论】:

      猜你喜欢
      • 2012-07-07
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      相关资源
      最近更新 更多