[英]Using a variable while defining another variable for a model in django
Basically what I want to do is this: 基本上我想做的是这样的:
class A(models.Model):
a_number = models.FloatField()
class B(models.Model):
a = models.ForeignKey(A)
b = models.FloatField(default=self.a.a_number)
I understand I can't use self while defining the variables, but is there a workaround for this? 我知道在定义变量时不能使用self,但是有解决方法吗? What if 'a_number' was a method instead of a variable? 如果“ a_number”是方法而不是变量怎么办?
I know i could make a method like this in B: 我知道我可以在B中制作这样的方法:
def b(self):
return self.a.a_number
But I need to get the value of 'a_number' right as I create the object in B so this wouldn't work. 但是我在B中创建对象时需要正确获取'a_number'的值,所以这将无法工作。
Implement a clean() method to set the default value for b
. 实现clean()方法来设置b
的默认值。
class B(models.Model):
a = models.ForeignKey(A)
b = models.FloatField()
def clean(self):
if self.b is None:
self.b = self.a.a_number
The Django documentation linked above suggests clean()
as the way to automatically provide a value for a field: 上面链接的Django文档建议使用clean()
作为自动为字段提供值的方法:
Model.clean() Model.clean()
This method should be used to provide custom model validation, and to modify attributes on your model if desired. 应使用此方法提供自定义模型验证,并根据需要修改模型上的属性。 For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field: 例如,您可以使用它为字段自动提供一个值,或者进行需要访问多个字段的验证:
(example omitted)
Remember to call clean()
before calling save()
on your model. 记住在模型上调用save()
之前先调用clean()
。 If you use the Django admin site, then clean()
is automatically called when an object is created or updated on that site. 如果使用Django管理站点,则在该站点上创建或更新对象时会自动调用clean()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.