#28857: PostgreSQL Cast function shortcut
-------------------------------------+-------------------------------------
     Reporter:  Jurica Železnjak     |                    Owner:  nobody
         Type:  Bug                  |                   Status:  new
    Component:  Database layer       |                  Version:  1.11
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:  postgres,orm         |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  1                    |                    UI/UX:  0
-------------------------------------+-------------------------------------

Comment (by Jurica Železnjak):

 models.py
 {{{
 from django.contrib.postgres.fields import JSONField

 class SensorData(BaseModel):
     timestamp = models.DateTimeField()
     data = JSONField()

 """ sample value for data: {
           "Temperature": 19.9,
           "Relative Humidity": 29.4,
           "PM2.5": 9.8,
           "TVOC": 79.0,
           "CO2": 476.0,
           "CO": 0.0,
           "Air Pressure": 977.1,
           "Ozone": 21.3,
           "NO2": 68.1,
           "Timestamp": 1511770361,
           "DateTime": "2017-11-27 09:12"
         }
 """
 }}}

 {{{
 from django.db.models.functions import Cast
 from django.db.models import Func, Avg, FloatField

 class ObjectAtPath(Func):
     function = '#>>'
     template = "%(expressions)s%(function)s'{%(path)s}'"
     arity = 1

     def __init__(self, expression, path, **extra):
         # if path is a list, convert it to a comma separated string
         if isinstance(path, (list, tuple)):
             path = ','.join(path)

         super().__init__(expression, path=path, **extra)


 SensorData.objects.all().aggregate(temp=Avg(Cast(ObjectAtPath('data',
 'Temperature'), output_field=FloatField())))
 }}}


 I think this should be enough to reproduce the error.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/28857#comment:2>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/064.563f0adba3ca1aedddb90dcdfaf35440%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to