django - ordering queryset by a calculated field

后端 未结 6 709
故里飘歌
故里飘歌 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:52

    I find that without the *args and **kwargs in the save method, it returns an error. And as celopes stated, this is only a solution if you don't mind materializing the computed field in the database.

    class Foo(models.Model):
        A = models.IntegerField(..)
        B = models.IntegerField(..)
        C = models.ForeignKey(..)
        D = models.IntegerField(..)
        E = models.IntegerField(..)
    
        def save(self, *args, **kwargs):
            self.D = self.A - self.B
            self.E = self.A - self.C.X
            super(Foo, self).save(*args, **kwargs)
    
        class Meta:
            ordering = ["E", "D"]
    

提交回复
热议问题