数据库查询的结果作为Django模型字段的默认值? [英] Result of database query as default value for Django model field?
问题描述
class Aref5(models.Model):
name = Aref5.objects.all.order_by('id')[0]
Rthink = models.TextField(max_length=2000, blank=True, default=name)
<....>
我想将默认值
的值设置为 Rthink
是最后一项的 id
。
I would like to have the default
value of Rthink
be the id
of the the last item.
使用上面的代码,我得到错误,指出无法识别 Aref5
。如何在 Aref5
的定义内访问现有的 Aref5
实例?
With the above code I get an error saying that Aref5
is not recognized. How can I access existing Aref5
instances within the definition of Aref5
?
推荐答案
这里有两个问题。一种是,如果这行得通,每当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.
这篇关于数据库查询的结果作为Django模型字段的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!