thomas
thomas

Reputation: 1885

How to make Django query using extra() portable accross database backends?

I have a little project that involved article archive browsing by year of publication.

I used the trick given in this other question to build a list of article publication years and article counts for those years. It works pretty well on my test server with SQLite. Since the production server will rely on PostgreSQL I am looking for a way to achieve the same thing in PostgreSQL and ended up toying with the EXTRACT keyword. I use something like "import settings" to detect the current database backend and execute the right query.

My point is all of that look more and more like a dirty & crappy hack to solve an issue in a very inelegant, untestable and poorly maintainable way. As a web programmer beginner I ask my experienced elder,

How would you deal with that correctly ?

Upvotes: 1

Views: 291

Answers (1)

Tommaso Barbugli
Tommaso Barbugli

Reputation: 12031

As an option to the raw sql:

You can calculate the count per year with the ORM (e.g. How to use Django ORM to get a list by year of all articles with an article count )

Then you store that value somewhere (in a model or in cache ...) in order not to be overwhelmed by the slowness of the ORM calculation.

Upvotes: 1

Related Questions