![](/img/trans.png)
[英]What is the most elegant / pythonic way of introducing large integer constants?
[英]What is the most elegant or Pythonic way to initialise a Django object?
我是 Python 和 Django 的新手,但我觉得必须有一种比我发现的更简洁的方法来实现这一点。
我有一个 Django model ,它的日期属性具有非平凡的默认值,这意味着我需要一些逻辑来设置它。 我已经尝试了几种方法,但不幸的是,这是迄今为止唯一对我有用的方法(在weeks
内的models.py
应用程序中):
def first_day_of_next_week():
return timezone.now().date() - datetime.timedelta(days=timezone.now().date().weekday() +
datetime.timedelta(days=7)
class Week(models.model):
start_of_week = models.Datefield('Date of the first day of the week',
unique=True, default=first_day_of_next_week())
我非常不喜欢 function 像这样漂浮在任何 class 之外(但没有经验知道它是否真的很糟糕)。 我已尝试将其合并到 static 或 class 方法中,或在一周内的__init__
进程中,但无法使任何这些方法正常工作(特别是, __init__
劫持复杂)。
现在我有 Week model 工作,我想从views.py
用Week.objects.get_or_create()
实例化周,但在这里我遇到了我需要相同的first_day_of_next_week()
逻辑才能在views.py
中访问的问题。 (这促使我尝试将逻辑转移到 static 或 class 方法,可以从views.py
访问。)我可以将first_day_of_next_week()
复制粘贴到views.py
中,它可以工作,但感觉不对种种原因。 我想我可以没有默认值,只在views.py
中保留创建周的逻辑,但我的印象是,最好尽可能在 model 中包含所有与周相关的逻辑。
有经验的 Python 程序员会做什么?
Django 型号仍然是 python 类。 您可以使用__init__
进行初始化,正如 python 所指的那样:
def first_day_of_next_week():
return timezone.now().date() - datetime.timedelta(
days=timezone.now().date().weekday() + datetime.timedelta(days=7)
)
class Week(models.model):
start_of_week = models.DateField(
'Date of the first day of the week', unique=True
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.start_of_week = self.start_of_week or first_day_of_next_week()
我还建议这样做,而不是使用auto_now
或auto_now_add
DateField、DateTimeField 关键字,否则您将无法在测试中将自己的值传递给这些字段,django 将在数据库保存期间覆盖您的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.