更新时间:2023-01-30 10:28:26
这里有两个问题。一种是,如果这行得通,每当Django启动时, name
就会被计算一次,并且每个 Aref5
实例将获得相同的默认值。另一个是尝试访问其定义内的类会导致错误。
There are a couple of problems here. One is that if this were to work, name
would be computed once whenever Django started up, and every instance of Aref5
would get the same default value. The other is that trying to access a class within its definition causes an error.
默认值
参数的 TextField
(或任何 Field
子类)可以是可调用的,而不是值,在这种情况下,只要创建新对象。像这样的东西应该起作用:
The default
argument to a TextField
(or any Field
subclass) can be a callable instead of a value, in which case it will be called whenever a new object is created. Something like this should work:
Rthink = models.TextField(max_length=2000, blank=True, default=lambda: str(Aref5.objects.latest('id').id))
由于表达式涉及 Aref5
出现在函数体内,没有立即进行评估。
Since the expression involving Aref5
appears inside a function body, it's not evaluated right away.