简体   繁体   English

如何在Django模型中轻松创建计算字段?

[英]How do I easily create a calculated field in a Django model?

No, I don't want a property . 不,我不想要房产 I really don't . 我真的没有 What I want is what I asked. 我想要的是我问的问题。


Due to subclassing requirements, I'm looking for a way to generate one field from a set of two others and store this computation in the database. 由于子类化要求,我正在寻找一种方法从一组另外两个生成一个字段并将此计算存储在数据库中。 Not a property in Python, not an SQL calculation, a pre-calculated field that is updated on save and stored, as is, in the database. 不是Python中的属性,不是SQL计算,是在数据库中保存和存储时更新的预先计算的字段。

For example: 例如:

class Help(models.Model):
    title = models.TextField()
    body = models.TextField()

class SoftwareHelp(Help):
    about_software = models.ForeignKey('Software')

Regardless of what a user enters in the title field, I want it to say "Help for " once save is clicked. 无论用户在title字段中输入什么内容,我都希望在点击保存后说出“帮助”。 In reality, the code has more fields, but this explains the principle. 实际上,代码有更多的字段,但这解释了原理。

I know its possible to do this by overriding the save() method, but wanted to make sure I wasn't saving to the database twice, and want to know if there is another better way. 我知道可以通过覆盖save()方法来做到这一点,但是想确保我没有保存到数据库两次,并想知道是否还有另一种更好的方法。

I think the easiest way is to override the save method. 我认为最简单的方法是覆盖save方法。 I don't see any reason why it should save to the database twice. 我没有看到任何理由为什么它应该保存到数据库两次。

class SoftwareHelp(Help):
    about_software = models.ForeignKey('Software')

    def save(self, *args, **kwargs):
        self.about_software = 'Help for %s' % self.title
        return super(SoftwareHelp, self).save(*args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM