4

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.

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. 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.

Community
  • 1
  • 1

1 Answers1

2

I think the easiest way is to override the save method. 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)
ilse2005
  • 11,189
  • 5
  • 51
  • 75
  • This was pretty much what I had to do. –  Mar 14 '16 at 00:57
  • Seems like `pre_save` is a better candidate for this. Though, how do I do this if I want `about_software` to be set as soon as I create an instance of that model? Edit: Hmm, never mind, `pre_save` is for a `Field`, not the `Model`. – FMCorz Mar 25 '17 at 08:57