在djang为模型定义另一个变量时使用变量

2024-03-28 10:59:16 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上我想做的是:

class A(models.Model):
    a_number = models.FloatField()


class B(models.Model):
    a = models.ForeignKey(A)
    b = models.FloatField(default=self.a.a_number)

我知道在定义变量时不能使用self,但是有解决方法吗?如果“一个数字”是一个方法而不是一个变量呢?你知道吗

我知道我可以在B中做一个这样的方法:

def b(self):
    return self.a.a_number

但是在B中创建对象时,我需要得到'a\u number'的正确值,这样就不起作用了。你知道吗


Tags: 方法selfdefaultnumbermodelreturn定义models
1条回答
网友
1楼 · 发布于 2024-03-28 10:59:16

实现clean() method来设置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

上面链接的Django文档建议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)

在调用模型上的save()之前,请记住调用clean()。如果您使用Django管理站点,那么在该站点上创建或更新对象时会自动调用clean()。你知道吗

相关问题 更多 >