user
user

Reputation: 445

Django - Order by custom function

I have multiple projects in my subprogram, each with a different cost which I'm calculating in a custom function in my project model. How can I create a subprogram function that returns a list of projects ordered by the costs function in the projects model? Is this possible todo?

Subprogram model:

class Subprogram(models.Model):
    title = models.CharField(max_length=100)

    def projects_sorted(self):
        return self.project_set.all().order_by('costs') 

Project Model:

class Project(models.Model):

    name = models.CharField(verbose_name="Name", max_length=100)
    subprogram = models.ForeignKey(Subprogram, on_delete=models.CASCADE)

    def costs(self):
        costTotals = 0
        costs = self.costs_set.all()
        for bcost in costs:
            costTotals += bcost.cost
        return costTotals

Upvotes: 0

Views: 65

Answers (1)

Daniel
Daniel

Reputation: 3527

Something like this might work (untested):

from django.db.models import Sum

class Subprogram(...):

    ...

    def projects_sorted(self):
        return self.project_set.annotate(
            total_cost = Sum('cost_set__cost')
        ).order_by('total_cost')

Upvotes: 1

Related Questions