Should I use raw SQL queries or something else?

371 views
Skip to first unread message

dmemb...@robottions.com

unread,
Jun 26, 2018, 8:00:59 AM6/26/18
to Django REST framework
After using Django for 4 months and enjoying it, now I'm trying DRF. While it's suited for most of my needs, I found an issue and I don't know how to deal with.

Let's say I have a TrainTravel model, with fields such as: passengers, average_km_hour, arrival_timestamp, departure_timestamp, and so on.

It's easy to query DRF for all TrainTravel , or for just all Trains with at least 50 passengers or Trains with an average of 150km/h.

The problem is when I want to do big queries, and those queries will return fields that don't exist in the model of the database. I'll explain:

Let's say I want a query that returns the average of passengers by day on the last 2 months, grouped by day and the average km/hour.

With normal SQL I would query the database and just return 'average_passagers', 'average_km_hour_by_day' and 'datetime' (the actual fields are a random example). But in DRF I can:

1) Get all TrainTravel objects instances and manipulate the data with Python: Super slow if I've to pull every register on the database
2) Perform a raw query with SQL. The problem is that it doesn't correspond with any existing model in the API. And I create a new model for every query, it will create a new table in the database.

So, in short: Sometimes I want to perform queries in the database that don't return the same fields of any model (sometimes I get info from 3 tables), but I just want to return a Json from the query.

It is DRF for me in this case?

gordon

unread,
Jun 26, 2018, 8:06:47 AM6/26/18
to django-res...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Julio Biason

unread,
Jun 26, 2018, 8:11:41 AM6/26/18
to django-res...@googlegroups.com
Hi Dmembrives,

If I'm not mistaken, you can add calculated fields in DRF serializers. So you can add @property fields (calculated values) on your models and just return those values. You can see an example of a calculated field here: https://docs.djangoproject.com/en/2.0/topics/db/models/#model-methods

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+unsub...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
Julio Biason, Sofware Engineer
AZION  |  Deliver. Accelerate. Protect.
Office: +55 51 3083 8101  |  Mobile: +55 51 99907 0554
Reply all
Reply to author
Forward
0 new messages