Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 599987
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T16:33:29+00:00 2026-05-13T16:33:29+00:00

I have a model which have a function to calculate the difference between two

  • 0

I have a model which have a function to calculate the difference between two fields
Example:

Class MyModel(models.Model):
    fieldA = models.FloatField()
    fieldB = models.FloatField()

    def delta(self):
        return self.fieldA - self.fieldB

Id like to use this model in a GenericView. I can use the function delta as an extraContext but also id like to include the sum of all Delta results in the template, in this case I have to make an aggregate but again since delta is not a DB Field nor a Model Field I cant use it in an aggregate function.

How can accomplish this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T16:33:29+00:00Added an answer on May 13, 2026 at 4:33 pm

    One way to do this is to create a Manager and defines a function with the raw SQL query. Create the model object attaching the new calculated field referencing to the model class with self.model

    Class MyModel(models.Model):
        fieldA = models.FloatField() 
        fieldB = models.FloatField()
        objects = MyModelManager() #Binds the manager to the model
    
    
    Class MyModelManager(models.Manager):
        def ReturnDelta(self):
            from django.db import connection
            cursor = connection.cursor()
            cursor.execute = """SELECT fieldA, fieldB, fieldA-fieldB as delta
                                from MyModel_table"""
            result_list = []
    
            for row in cursor.fetchall():
                p = self.model(fieldA=row[0], fieldB[1]) #access the model associated w/ the manager
                p.delta = row[2] #adds the new field to the queryset
                result_list.append(p)
            return result_list 
    

    Almost a copy-paste from Django Documentation
    Then we can use the manager function in the extra-context dictionary of the generic view. and do algebraic operations without hitting the database unnecessarily.

    A better solution is create your own QuerySet class with a custom Manager. This allows to chain filters and return any computed value as a QuerySet attribute. Is taken almost directly from this snippet

    class CustomManager(models.Manager):
        '''
           An general purpose manager which allows to filter a queryset
           and chain filters
           "Constructor": CustomManager(CustomQuerySetClass)
        '''
    
        def __init__(self, qs_class=models.query.QuerySet):
            super(CustomManager,self).__init__()
            self.queryset_class = qs_class
    
        def get_query_set(self):
            return self.queryset_class(self.model)
    
        def __getattr__(self, attr, *args):
            try:
                return getattr(self.__class__, attr, *args)
            except AttributeError:
                return getattr(self.get_query_set(), attr, *args)
    
    
    class MyModelQuerySet(models.query.QuerySet):
        '''
           A very specific queryset designed to return a computed value (this
           time a sum of all rows values)
        '''
        def filter(self, *args, **kwargs):
            qs = super(MyModelQuerySet, self).filter(*args,**kwargs)
            sum=0
            for row in qs:
                sum += row.delta    #use a callback to prevent from caching
            setattr(qs, 'sum',sum)
            return qs 
    
    
    class MyModel(models.Model):
        objects = CustomManager()    #Binds the manager to the model
        fieldA = models.FloatField() 
        fieldB = models.FloatField()
        def delta(self):
            return self.fieldA - self.fieldB
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Model which has some constants defined, like below: class Order(models.Model): WAITING
I have this code which calculate route between tow places function createDrivingRoute() { $(#nav).html();//CLEAR
I have a model which has a field status definde as: class Model(models.Model): ...
I have 3 django models (simplified for this example): class Fighter (models.Model): name =
I have a model which looks like this: //myModel.js define([], function () { var
I have a model which contains lists of other models, which also contains lists
I have a model which has a certain behaviour implemented. class X { ....
I have Django model that looks like this: class Categories(models.Model): Model for storing the
So I have two models, a Ranking model and a UserRanking model. The app
I have a class which models online campaigns i.e. people clicking through to the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.