Add Field to QuerySet to Store Computation Results Django.How

Author avatar wrote on 06/06/2022

Way 1: Annotate() & Query Expressions

  • https://docs.djangoproject.com/en/3.2/ref/models/expressions
  • How many chairs are needed for each company to seat all employees?
    
    from django.db.models import F
    
    company = Company.objects.filter(
       num_employees__gt=F('num_chairs')).annotate(
       chairs_needed=F('num_employees') - F('num_chairs')).first()
    


    Way 2: Set anything on a python object

    
    for obj in self.model.objects.all() :
        obj.score = total_score / total_posts # This will work even if obj does not have a score attribute
    

    In template
    
    {{ obj.score }} 
    

    However, if the calculations you're doing can be done in the database, you should look into annotate.

    Way 3 Modifying the queryset, Ensure you don't call .all()

    
    qs = foo.objects.all(bar=1); 
    for obj in qs.all(): 
        obj.caz = 1;
    

    In template
    
    {{ obj.caz }}
    

    Way 4 Use a dictionary

    
    newthing = {}
    newthing['your_key'] = to_add
    

    In template
    
    {{newthing.your_key}}
    

    Resources
  • https://stackoverflow.com/questions/12118776/django-add-field-to-queryset-to-store-computation-results
  • https://docs.djangoproject.com/en/3.2/ref/models/expressions/