# How (and why!) to build a Django based project with SQLAlchemy Core

Source: https://djangotv.com/videos/djangocon-europe/2019/djangocon-2019-how-and-why-to-build-a-django-based-project-with-sqlalchemy-core/
Date: 2019-04-21
Speakers: Gleb Pushkov, Speaker 2, Speaker 3, Speaker 4, Speaker 5

## Summary

Gleb Pushkov explains when combining Django with SQLAlchemy Core is useful, especially for data-analysis applications dominated by large aggregations, complex joins, and performance-sensitive queries. Django’s ORM is a good default for most application features, but its model-first abstraction limits some SQL shapes, join conditions, recursive CTEs, and direct control over execution; SQLAlchemy Core stays close to SQL and makes nested selects, grouping, and dynamic query construction more explicit. He outlines integration choices, connection pooling, table definitions and reflection, and testing pitfalls caused by maintaining separate Django and SQLAlchemy connections and transactions. The trade-offs include harder setup and debugging, slower or more involved tests, extra connections, and losing direct compatibility with ORM-dependent tools such as Django admin and pagination.

## Transcript

### [00:01] Motivation and Use Cases

**Gleb Pushkov:** [00:01] Hello, my name is Gleb. I'm a software developer from Ukraine, Kyiv, working with Python Django more than six years. Currently employed at Django Stars. And today I want to show to share with you actually a lot of information, so I have to be really fast to fit on the time. And I hope we will have some time for questions, but I don't promise it And actually I want to start with motivation. Why should we actually need to mix Django and TSK or Alchemy Core, which benefits we can get and in which cases it could be useful for us? So actually the main use case is data analysis application. So your application works mostly with aggregations, so you don't work with like

[00:47] single lines of table you don't have REST API or you don't modify single rows of your data so you're only interested in aggregations and calculations So you likely will have a lot of data, so you have your queries to be really performant and precise. And maybe you could have some if you have some pattern of the your pages you could build some wire which will generate such advanced queries for you. So you maybe have such wire and it's really easy to build it with SQL Alchemy and maybe you also want to you design your queries in SQL in the console, you check performance, how it works, then you satisfy it and you want to move them to Python.

[01:32] It's really easy to do it with SQL Alchemy also. And maybe your data source which you work with doesn't natively supported by Django and maybe third-party applications which provide the support and integration, they are not fit your needs. So this the main use case then you likely should s check this tool. So I really like Django. I really like Django RM, it's a fantastic tool. You even kind of forgot how to SQL. But yeah it's greatly evolves. It allows you to focus on the implementation of business features instead of doing some low level stuff so you really can pro deliver your

### [02:17] Django ORM and SQLAlchemy Core

**Gleb Pushkov:** [02:17] Features much faster and more reliable way. And in last releases Django got a lot of cool features, so like subqueries, window functions, so you already heard it yesterday. From Sigurd and so you have less reasons to switch to RAW SQL. But if we build the data analysis application, Django RAM has its own specific so let's talk about this So for example if we want to we have properties and we have owners and we want to find for example five properties which in the city which start with the letter key and we want to get the username of the owner So we do in selector weighted which performs

[03:03] left outer join. We can also limit amount of fields which we want, so query is a bit simpler, but Yeah, in Python it's less readable. So I want you to focus on these two lines. So as you see, we have left outer join and we have limit. And if we See the explain how in which order this operation performed. We see that first of all we find the properties which we are interested in. It's huge amount of properties. And only then we join to each of the row of the property, we join all nurses and only after that we do a limit So this is not performant, this is not the way that we want to execute the query. Likely we want to have a query like this

[03:49] So we have nested select, it's like correlated subquery, and we select only fields we're interested in, so we are doing limit there. And then we join users to these five rows. So it's very performant, it's good, believe me, you have not to read it. And with SQL Alchemy Core such query will look like this. And as you see on the first line, we simply build this nested select which doing a limit so this subquery and we simply insert it in other select and perform join. So it's really straightforward and you can really fast understand what's going on underneath in Django RM this query will look like this. That's why

[04:35] because all your query which you built it starts from model, model like declare for you the from clouse which will be used in the query. So the subqueries that we have, they could be used in the select where having, but we can't put it into the from, so we can't make select from select. So we of course can build similar feature similar query. We will can get a primary case of the properties which we're interested in and put it into subqueries. So it's also performant, so it's okay. But this example showed us that actually Django RAM and SQL Alchemy Core, they are on different wires and they are designed to solve different needs.

[05:21] And different problems. So in Django Stack we have underlying non-public API which is a query set. query but documentation doesn't recommend to use it but in your SQL Alchemy Core it's like on top of the SQL, so it's very close to SQL. And as you can see it's very readable, it's really easy to understand, and you can build your query easily. On the other hand, as you see Django ram sample, the first filter it's would be actually the WER clouds. the values it would be a group by, annotate would be a list of fields, a list of aggregations which you want to perform on the query. And the last filter would be actually a heading clause which will apply on the top of your query

### [06:10] Composable SQLAlchemy Queries

**Gleb Pushkov:** [06:10] So it's not string directly mapped to the SQL level. And when you building queries with jung with or on ORM, such queries you really feel that you don't have enough freedom. And I want to show one more example. For example, we have two tables. We have properties and owners, and in properties table we have apartments and we have buildings. So apartments place it in buildings and they have this building ID so it's self-relation to the table. So let's start building our fancy query with scale alchemy. We Doing simple select from the properties table, we just select information which we want, like building ID, owner and sale price.

[06:57] And we want to get the properties which are for sale and which has sale price. So simple select. Then we can add more level where we're doing select from the previous select. So but here we want to replace the owner ID with user with username. So we have to join users and we simply replace it. Then we decide that we need to go deeper and we add one more level. So we built level three in which So we have building ID, so we can group buy our apartments and get the total price of the all apartments which are for sale in this building. So we do in group by, we apply the functions that we need and

[07:42] it's very readable. And on the last level we can we have only unique building ID so we can join building related information here, so we have only roles which we want to join so we can add like total apartment amount to the to the building so Your query would be look like this so it's select from select from select from select and on each level you do in like join group by again join so This is the freedom I'm talking about. So SQL Alchemy allows you to build any type of such queries, which is really cool. Another example about

### [08:27] Subqueries and Aggregations

**Gleb Pushkov:** [08:27] Django limitations and readability. Imagine the case we also work with properties. So we want to find the first price which is bigger than one million and then we want to get all properties which has the same price which we just found. So the query we want to build is like this so we put like where sale price equals to and aggregation over all the table by our condition. Let's try to do it in Django. Our first attempt would be to use aggregate, but aggregate queries I evaluated immediately so it will doesn't work for us because we have two queries to database to trips which is not performant. So we want to use subqueries.

[09:14] Subqueries use with worked with query sets. And s that's why we have to change our minimum aggregation minimal to the such trick like order by, ascending by price and get the first one. So it will get the minimal price. But as you see in our select we have also order by limit one and it's it's not readable and if you see order by or distinct account in your SQL query they are not performant. And this is not the way that you want to build queries if you work with big amounts of data. So we can leverage underlying on public API, which I mentioned. earlier. So as you see we have a query set

[10:00] dot query add annotation. So we manually add this annotation which we want. Its summary says that it should be applied over the old table And we actually get the query which we want. But yeah, it's not recommended in the Django documentation, so it's up to up to you do you want to use it or not. And one more way, we can subclass subqueries and we can override template. But yeah we also get the SQL which we want, but this solution is to RAW as for me. So on the other hand with the SQL alchemy this is pretty straightforward. As you see on the first line we build in also select and in the second line in the where we simply put this select into the condition and it will do all the magic

### [10:49] Joins and Recursive CTEs

**Gleb Pushkov:** [10:49] and we will get the query which we want. More limitations in Django RM, joins. You can't join tables which are not related. If they don't have relation, you totally don't have ability to do joins. You can't do right outer join. But yeah, it's very rare, but sometimes it happens, but I have to mention it. Also Django decides for you when to make inner or left outer join and you not you doesn't know what's happened underneath if you don't print query or you can you can't change it from left outer to inner if you can if you want to simply cut out some rows which has new values. And

[11:34] Django also generates for you this join condition on condition, and you can barely customize it. You can't get rid of it, you can't change this default. You can only use filter duration, which will add nth. And that's actually all. So you can't provide OR some more explicit logic, some more complex logic to do join. Recursive command table expressions are also not supported by Django yet. It's useful when you work with the roles which has like parent ID and there are it's point to another row which has parent ID, another row or another row and you want to

[12:19] Take all of them and make some aggregation or calculation over them So currently you can do it with RAW SQL or SQL Alchemy. Also it there is a library like Django City Forest. But it has limitations and it implement implemented via extra but extra would be deprecated so it's not recommended to use so this library is not usable currently One more example about how Django syntax is far from SQL. So It's actually from Django documentation. I like it very much. So as you see we have book, we have authors, we can have store stores. And if we do in this annotation in one line, so of another

[13:05] aggregation of multiple tables, so we get the wrong aggregation. So in fact instead of subqueries it will be a joint. So you simply multi multiply amount of rows and all your aggregation will produce wrong result. Count could be fixed with distinct true, so it will kick out all rows which redundant but actually other aggregations which will produce the result which you don't actually want to get So this is if you not read documentation precise in us, you could fail in such issue. So to sum up, it's It's hard to read advanced queries in Django. It's hard to understand what's going on

[13:51] SQL level. And yeah, it takes time to convert query from SQL to Python if you design it somewhere and it's not so flexible so some parts you can't change or you have to change your original SQL query to make Django to be able to build it. But this is not a problem in ninety-five percentage of the cases. 95 is a number from my head So usually it's okay we have ability to switch to RAW SQL and if you have few such places it's not an issue and it doesn't hurt maintainability of our pro product but if you build a data analysis application where you have only aggregations, it really could hurt.

### [14:38] SQLAlchemy Integration Setup

**Gleb Pushkov:** [14:38] It's like the same slight as you saw. So it's it's okay to look at such tools like SQL Alchemy for such type of project. So here is a brief tutorial for you how to start and what you have to expect with this integration. First of all you have to create engine it's a global variable which describe your connection. To database and SQL Alchemy comes by default with connection pooling functionality. So you get a Q pool but if you want your connection to behave the same as a Django work like Django connection, you have to disable pooling with no pool. From architecture point of view, your application would look would look like this.

[15:24] So you have one instance, you have UGI, you have four workers which are processors, each of them configured to have eight threads. and each thread manage its own connection so you have 32 Django connections and 32 SQL Alchemy connections so likely a waiter when you get the user so maybe when you instances have start scaling So you would like to add some connection pull-in wire like PG Bouncer, for example, if you use Postgres because for Postgres. It forks a process for each connection, so it's quite expensive to hold connections. It takes at least 10 megabytes of RAM. So if you have two instances, you just simply lost 1.

### [16:10] Table Definitions and Query Results

**Gleb Pushkov:** [16:10] 2 gigabytes of RAM simply to hold these connections. So that's why connection pooling wire would be recommended for you in if your application grow. Then you need to understand how you will work with the tables. So you have few options there are two libraries which allows you to integrate a scale alchemy with Django. First of them Alchemy it's has a mapping of the Django fields and it's built SPL alchemy representation of this field of the stables and attach it to the models. Another one, stable reflection, it's used it's SQL Alchemy technique which allows you wh like here you say okay I have this table I want to get

[16:55] Python representation of this table. So it generates it for you, but it takes some time, so you have to cache it maybe on application launch. Also you can define your tables explicitly or define within line expressions. If you define explicitly it's look like Django models. But you can keep it more simpler because we only read the data, so you can provide only names of the table of the columns. But I also advise you to specify foreign keys because SQL Alchemy automatically pick up the this relation so you have not to specify on condition for joints so it would be a bit simpler in code. How

[17:40] you can use such tables So you build a query and you have C attribute which stores cons and you use it like a reference and result which you get each row of result is raw proxy which actually behaves like name it tuple or like tuple or like dictionary so it's very handy and also it's possible to define your tables and columns with inline expressions. They are lightweight. So you simply put the names in the query or but if you have to keep the reference for the column to the table which is refers to, you can define it like this so the usage would be like on the previous slide.

### [18:26] Testing Across Two Connections

**Gleb Pushkov:** [18:26] Actually that's all what you need to know. But did somebody say tests death is not so straightforward. It has some pitfalls and something which is worth to mention. So first of all, if you remember we created in gen as a global variable, so once the interpreter will read this line, it will evaluate it. So we can't use overwrite settings, we can't use PyTest fixtures or hooks to change this setting because our line would be already evaluated. So likely you will have to introduce a function like this. So if it's test it adds add test prefix for you, otherwise you will lose your data.

[19:11] Another interesting feature which I faced it's how Py test work with cursors. So if you have a result proxy it's actually a wrap around a DBRP cursor and you have ability to iterate over the roles so you don't wad all of them into memory you're just iterating across them So you have a function like process rows and maybe somewhere inside there is you write test and there is exception and it fails. So py test will mark this test as failed and it will hang on forever because it doesn't Allow Garbage Collector to close the connection. Usually it's does usually it's performed automatically

[19:56] So you have to do such tricks like for example, write a decorator which applied to this function which iterate and produce exception, for example. In case of some error. So you simply run across the all arguments and if it's result proxy if it's your cursor you close and erase exception. But it yeah looks not so straightforward. And the most important thing which you have to keep in mind when you develop such type of application is that you have two connections and each of these connections have its own transaction isolation level So if you use test case and you populate the database with model mummy or factory boy,

[20:41] it will happen in Django connection. So for test case, in start of the each test Django creates transaction for you, but it doesn't commit it in the end, it makes a rollback. So transaction is never committed and SQL community doesn't see the data which was produced in this test. So this some kind of issue but still you can use test case in your application but Just keep in mind that yeah it when you write tests for the code which works with one connection and you populate the test database with the same connection. But yeah if you populated the data with SQL Alchemy connection, you have to clean your tables by yourself between the tests, maybe with hooks or fixtures.

[21:30] And also it's theoretically it's possible to share the data which was created and not committed, so you need to change the turn transaction isolation level on the SQL alchemy. connection to read uncommitted but yeah it's not recommended but it's it's possible. And also you can use transaction test case and there is no issues with that. So it's fine. But such tests work slower because there are in how this tr transaction test case works. They do in a post-migrate signal between each test so they truncate all the tables which have models. and then they launch post migrate signal which creates permissions and content types

### [22:16] Integration Drawbacks

**Gleb Pushkov:** [22:16] So it takes some time so such tests would be slower Yeah, and if you work with tables which doesn't have relation to Django models, you also have to clean up them between tests by yourself. So drawbacks. It's a bit hard to start because it's not too much information about such integration and there are no such like tutorial like okay you have to do this. But documentation of a skill alchemy is quite good but sometimes it work some examples but overall it's it's nice to work with. And yeah you can find that it's not very easy to work with if you want to debug your query which you made in python so you print it into the console

[23:04] and you s you will see that all parameters which you have maybe twenty or thirty of them if it's hard query They it would be a placeholders instead of values which you wanted to be there. So it's a bit annoying to insert them manually because this functionality is done by db which doing this safe insert of the parameters into the query so a scale alchemy doesn't have such functionality of escaping your values to omit this in injection SQL injections. And yeah it's there are some solutions but it's not so straightforward so it's a bit annoying. And you have

[23:49] slower tests Because likely you will use more transaction test cases which are slower, but it also depends. And yeah, you have more connections to database, but the most Important thing to keep in mind that you can't no longer use libraries like Django Futures or Pagination because they designed it to work with query sets and now you have only like dictionaries or tuples or lists so you have to find some query set independent libraries or come with your own solutions to cover this gap. But let's talk about benefits. So you actually get the full control over SQL level, which is really cool and it gives you freedom to build whatever you want.

### [24:34] Benefits of SQLAlchemy Core

**Gleb Pushkov:** [24:34] Yeah, it's faster to express a SQL in Python code. So if you have some data analysis guy which bring you tons of queries and say, okay, build these queries in Python, it's really easy to build them, modify yeah, and if you have some wire which creates such queries for you dynamically, you have in SQL Alchemy you have all obstructions over SQL, so you can use them like building blocks and you can build whatever you want. It's very handy to do this. And yeah, of course readability, maintainability, and performance, because actually what you design it in SQL, you generate it from Python so if you know SQL well in us so you will do correct queries and performance.

[25:22] That's all. I don't know do we have time for questions.

### [25:42] Questions

**Speaker 2:** [25:42] We do have a few minutes for questions. So if anyone wants to come to the front or if we have anyone online with Django DjangoCon QA hashtag we can answer a few questions.

**Speaker 3:** [25:58] Hello, thanks for the talk. One question coming to my mind. You said you are having two database connections, which is obvious because you have Django and SQL Alchemy. Did you explore the possibility of writing a I think in SQL Alchemy it's a database dialect? Which would bridge over to the Django connection and reuse the underlying database API connection instead of having the two.

**Gleb Pushkov:** [26:25] Sorry, could you repeat?

**Speaker 3:** [26:27] So There would be the possibility to write a custom backend for SQL Alchemy, which would then reuse the connection from Django. Did you explore this?

**Gleb Pushkov:** [26:40] Actually there is a library. Currently it's under development, it's like Django SQL Alchemy and it tries to be inserted into the wire which generates these queries So there are some attempts to merge them together, but this is as I dev as far as I know they are currently under development and Likely it would be not so easy and straightforward. So I haven't tried this, but I'm not sure that this goods good way to move your application

**Speaker 4:** [27:12] Okay, thanks for the talk. It was interesting. I probably can guess the answer, but I wanted to know from you. You haven't talked about the admin stuff in Django. Would it be possible to use the SQLchemie with the admin Probably not.

**Gleb Pushkov:** [27:35] No. Stack, but the solution which I'm currently talking about, it's mostly about yeah designing your queries which would be displayed for the users maybe you can use it You if you start customizing a lot your Django admin maybe you can insert there, but it's n it will be not easily integrated and Django admin it's mostly It's ORM, so it works with single rows, but this is aggregation. So you can have built custom dashboard somewhere to show the numbers. Overall numbers but if you want to work with single roles so you have to stick with jango

[28:22] rem.

**Speaker 4:** [28:23] Okay thank you

**Speaker 2:** [28:25] We have a little bit less than one minute so we can answer about one more question.

**Speaker 5:** [28:30] Okay, I will try to be fast. So you mentioned in your talk that the you start usually with a big SQL query that you already have. So I was wondering if you explored to store that query as a stored procedure in the database and query and using query set to launch the stored procedures and what are the pros and cons compared to SQL ac in the project

**Gleb Pushkov:** [28:58] I think it's mostly about how do you then manage and maintain your storage procedures because if you have everything in Python code in Python project it's easily to manage to change and to influence in that. So I can say about pros and cons. It's From my point of view, it's mostly about how it will be maintainable in the long run. So my opinion it's better to have everything in Python and not move this functionality to database because it would be not so explicit and not transparent what will going on. So yeah.

**Speaker 5:** [29:40] Thank you.
