I have below model
from django.db import models
from django.contrib.postgres.fields import JSONField
import jsonfield
# from django.utils import timezone
from base_app.models import BaseModel
from django.db.models.functions import Cast
from django.contrib.postgres.fields.jsonb import KeyTextTransform
from django.db.models import Count, Sum
class UploadCableTrayDataManager(models.Manager):
def counts_only(self):
return (UploadCableTrayData.objects.annotate(thickness=Cast(KeyTextTransform("value", "Thickness"), models.FloatField())).values("Thickness", "Selection").annotate(thickness_count=Count("Thickness"), running=Sum(Cast(KeyTextTransform("value", "Length"), models.FloatField()))).order_by())
class UploadCableTrayData(BaseModel, models.Model):
"""
Model to store Cable Tray data
"""
order_upload_id = models.AutoField(primary_key=True)
Order_number = JSONField(null=True, blank=True)
Type = JSONField(null=True, blank=True)
Selection = JSONField(null=True, blank=True)
Height = JSONField(null=True, blank=True)
Width = JSONField(null=True)
Box_width = JSONField(null=True)
Box_height = JSONField(null=True)
Length = JSONField(null=True)
Inner_bend1 = JSONField(null=True, blank=True)
Inner_bend2 = JSONField(null=True, blank=True)
Thickness = JSONField(null=True, blank=True)
Rung_width = JSONField(null=True, blank=True)
Rung_height = JSONField(null=True, blank=True)
Distance_between_rungs = JSONField(null=True, blank=True)
project = models.ForeignKey('project.Project', on_delete=models.DO_NOTHING)
objects = UploadCableTrayDataManager()
def __str__(self):
return str(self.order_upload_id)
class Meta:
db_table = 'UploadCableTrayData'
And view.py
data123 = UploadCableTrayData.objects.counts_only()
But with this, I am getting below the object or I don’t know what is that. But I am expecting data from the database.
<django.db.models.query.QuerySet object at 0x000001999B6698E0>
I have tried the below query also, and getting the result almost as expected. Only RunningMeters coming 0. The sum is not working.
data = list(UploadCableTrayData.objects.filter(creator_id__in=selected_users).filter(date_added__range=(
selected_start_date, selected_end_date)).values('Type', 'Thickness', 'Width', 'Height', 'Selection').annotate(dcount=Count(['Type', 'Thickness', 'Width', 'Height', 'Selection']), RunningMeters=Sum('Length__value')).order_by())
This is what I got
'Type':'{"key": "type", "value": "pct"}'
'Thickness':'{"key": "thickness", "value": "1.2"}'
'Width':'{"key": "width", "value": "75"}'
'Height':'{"key": "height", "value": "25"}'
'Selection':'[{"key": "material", "value": "ms"}]'
'dcount':1
'RunningMeters':0