class Daily(models.Model):
rpt_date = models.DateField('Report Date', primary_key=True)
total_d_sors = models.IntegerField()
loaded_d_sors = models.IntegerField()
#diff_d_count
d_sors_missed_eod = models.CharField(max_length=300)
total_m_sors = models.IntegerField() #monthly
loaded_m_sors = models.IntegerField() #monthly
m_sors_missed_eod = models.CharField(max_length=300)
I have the above class in my models.py but when I display it through a view I need to have an additional column which will have the difference between two existing columns (total_d_sors and missed_d_sors) ie, diff_d_count=(total_d_sors - missed_d_sors)... can someone help? I'm seeing examples with cursor implementation; is there any other way?
Why don't you add a property on the model and calculate it on the fly as you're displaying it in your template?
class Daily(models.Model):
@property
def diff_d_count(self):
return self.total_d_sors - self.missed_d_sors
Then you can access it in your template or wherever via obj.diff_d_count
.
To find difference between 2 columns you can use,
1. annotate
2. F expression
Your query would be,
Daily.objects.annotate(diff=F('total_d_sors')-F('missed_d_sors'))
Sample working code with template,
from django.db.models import F
from django.template import Context, Template
context = Context({"daily_objects": Daily.objects.annotate(diff=F('total_d_sors')-F('missed_d_sors'))})
template = Template("{% for i in daily_objects %} {{i.id}} || {{i.diff}}. {% endfor %}")
template.render(context)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.