我有以下(简化)模型和工厂:
模型.py
class Event():
duration = FloatField()
start_time = TimeField()
finish_time = DateTimeField()
def save(self, *args, **kwargs):
self.finish_time = self.start_time + timedelta(hours=self.duration)
event_factory.py
from factory import Faker
class EventFactory:
date = Faker(
"date_time_this_month",
before_now=False,
after_now=True,
tzinfo=timezone.get_current_timezone(),
)
start_time = Faker("time_object")
duration = Faker("random_int")
但是,我的
save
方法提高了Warning: DateTimeField Event.finish_time received a naive datetime (2022-03-28 12:43:38) while time zone support is active.
date
由于tzinfo
参数而意识到,但start_time
很天真(我检查了django的timezone.is_aware()
),因为Faker中的时间提供者似乎不允许任何时区参数。
在factory-boy/Faker中获得假感知时间对象有什么建议吗?
尝试使用 FuzzyDateTime 对象,它们返回一个时区感知对象:https://factoryboy.readthedocs.io/en/stable/fuzzy.html?highlight=timezone
正如 @Bridge 所说,大多数 FactoryBoy 的内置模糊器已被弃用,取而代之的是 Faker 的等效项。请参阅https://factoryboy.readthedocs.io/en/stable/fuzzy.html
要在 Faker 中生成感知时间对象,您可以使用
tzinfo
参数:
from datetime import UTC
created_at = factory.Faker("date_time", tzinfo=UTC)