如何使用model_mommy模拟从timestamedModel继承的模型的已创建字段?

2024-05-16 17:56:50 发布

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

我正在尝试测试日期筛选器,但无法使用设置创建的日期妈妈。做(). 当我用model mommy创建对象时,created字段设置为对象创建的时间,而不是我传入的时间妈妈。做()

def test_mommy(self):
    today = arrow.now()
    yesterday = today.replace(days=-1)

    mommy.make('Model', created=today.naive)
    mommy.make('Model', created=yesterday.naive)

    model_1_created = Model.objects.all()[0].created
    model_2_created = Model.objects.all()[1].created

    self.assertNotEqual(model_1_created.strftime('%Y-%m-%d'), model_2_created.strftime('%Y-%m-%d'))

此测试失败,并出现断言错误:

^{pr2}$

我可能有一个误解模特妈妈是如何创造这些物品的。但我认为这应该创建它并正确设置创建日期。尽管看起来默认的TimestamedObject行为正在接管。在


Tags: selftodaymakemodelobjects时间allcreated
1条回答
网友
1楼 · 发布于 2024-05-16 17:56:50

我可以在创建对象后保存创建日期。我认为这也可以通过重写timestamedModel上的save方法来实现。但这似乎是更简单的解决办法。在

def test_mommy(self):
    today = arrow.now()
    yesterday = today.replace(days=-1)

    foo = mommy.make('Model')
    bar = mommy.make('Model')

    foo.created = today.naive
    foo.save()
    bar.created = yesterday.naive
    bar.save()

    model_1_created = Model.objects.all()[0].created
    model_2_created = Model.objects.all()[1].created

    self.assertNotEqual(model_1_created.strftime('%Y-%m-%d'), model_2_created.strftime('%Y-%m-%d'))

相关问题 更多 >