Reputation: 183
I have this model:
class User(models.Model):
uid = models.AutoField(primary_key=True)
email = models.EmailField(max_length=200, unique=True)
password = models.CharField(max_length=200)
name = models.CharField(max_length=200, default='')
contact = models.CharField(max_length=10)
cash_amount = models.IntegerField(default=25000)
share_amount = models.IntegerField(default=0)
def __str__(self):
return self.email
def total_amount(self):
return self.cash_amount + self.share_amount
How to write QuerySet for ordering the result on the basis of total_amount(), I tried below query:
User.objects.order_by('total_amount()')
But FieldError: Invalid order_by arguments: ['total_amount()'] comes.
Is there any other way possible of writing the query for ordering the result on the basis of cash_amount + share_amount without creating the total_amount().
Upvotes: 0
Views: 278
Reputation: 12613
You can try using extra
User.objects.extra(
select={'field_sum' : 'cash_amount + share_amount'},
order_by=('field_sum',)
)
Upvotes: 1