Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

288
Views
¿Cómo puedo reescribir un valor promedio por consulta MySQL de intervalo de tiempo de fecha como Django QuerySet?

Tengo la siguiente consulta de MySQL que muestra el valor promedio por intervalo de 10 minutos:

 SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(date_time) / 600) * 600) AS interval_date_time, AVG(some_value) AS avg_value FROM djangoapp_somemodel GROUP BY interval_date_time ORDER BY interval_date_time;

Por ejemplo, si tengo los siguientes 3 registros:

Identificación del producto fecha y hora algún_valor
1 2021-11-29 00:11:01 10
2 2021-11-29 00:16:15 20
3 2021-11-29 00:24:32 25

La consulta generará lo siguiente:

intervalo_fecha_hora valor_promedio
2021-11-29 00:10:00 15
2021-11-29 00:20:00 25

Sospecho que la consulta no es tan eficiente, pero quiero obtener el mismo resultado usando Django QuerySet.

Como referencia, mi modelo Django se ve así:

 class SomeModel(models.Model): item_id = models.AutoField(primary_key=True) some_value = models.FloatField() date_time = models.DateTimeField(auto_now=True)

Aquí está mi QuerySet actual:

 (SomeModel.objects .annotate(interval_date_time=F("date_time")) .values("interval_date_time") .annotate(avg_value=Avg("some_value")) .order_by("interval_date_time") )

Creo que necesito hacer cambios en la primera llamada al método de anotación. Cualquier ayuda sería apreciada ya que soy bastante nuevo en Django.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Podría ser más fácil usar RawSQL aquí si sabe que siempre trabajará con MySQL.

 ( SomeModel.objects.annotate(interval_date_time=RawSQL("FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(date_time) / 600) * 600)", ())) .values("interval_date_time") .annotate(avg_value=Avg("some_value")) .order_by("interval_date_time") )
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!