django - ordering queryset by a calculated field

后端 未结 6 704
故里飘歌
故里飘歌 2020-11-30 04:22

I want to have a model with calculated fields that I can apply sorting on. For example, let\'s say that I have the following model:

class Foo(models.Model):
         


        
6条回答
  •  情歌与酒
    2020-11-30 04:47

    I haven't presently got a Django install running, but I think what you're asking is how to do a custom save, such that D and E are automatically generated. I don't know what your ForeignKey's return on unicode is, so I'm assuming it's not a string and assigning "valueName" as token vlaue for the integer you want to usage.

    Anyway, it should go a bit like this:

    class Foo(models.Model):
        A = models.IntegerField(..)
        B = models.IntegerField(..)
        C = models.ForeignKey(..)
        D = models.IntegerField(..)
        E = models.IntegerField(..)
        def save(self):
            self.D = self.A - self.B
            self.E = self.A - self.C.valueName
            super(Foo, self).save()
    

    Anything prior to the last line of that (super()) will be PRE save, anything after is POST. That's really the most important point there.

提交回复
热议问题