<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sergey Bachurin on Medium]]></title>
        <description><![CDATA[Stories by Sergey Bachurin on Medium]]></description>
        <link>https://medium.com/@bachurin.sn?source=rss-998425d33551------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R1LpHCbj_rTm9-Fb7KP_gQ.jpeg</url>
            <title>Stories by Sergey Bachurin on Medium</title>
            <link>https://medium.com/@bachurin.sn?source=rss-998425d33551------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:49:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bachurin.sn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bad advice for a developer: don’t consider timeouts; let the user be surprised]]></title>
            <link>https://levelup.gitconnected.com/bad-advice-for-a-developer-dont-consider-timeouts-let-the-user-be-surprised-4bb9d9445fa?source=rss-998425d33551------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bb9d9445fa</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Sergey Bachurin]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 23:23:43 GMT</pubDate>
            <atom:updated>2024-01-16T23:23:43.574Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bad advice for a developer: don’t consider timeouts and let the user be surprised</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8EZWMDHv7tTX9lbzpWq1g.png" /><figcaption>“Broken microservices diagram” by Dall-E</figcaption></figure><p><em>When communicating with microservices or external services and disregarding correct timeout values, you will encounter troubles. It’s usually not a significant issue for retrieving data, as requesting the data again is possible. However, caution is necessary when providing an API that enables data creation.</em></p><p>Consider some API endpoint. The query must be handled synchronously, implying the user will receive a response only after the message has been written to the database.</p><p>Let’s start by assuming that there are practically no timeout limits (set to large values or disabled), and any request will be executed until the user receives a response. Initially, this approach might function adequately. However, as the data volume increases, users experience prolonged waiting times for responses, leading to high CPU loads on our servers and making them unresponsive. Consequently, we choose to refine our service by setting timeout values in our configurations. Additionally, we decide to make some API calls to another service.</p><p>Let’s make our service more realistic. For instance, it is constructed using Django with a PostgreSQL database and deployed using Gunicorn and Nginx. External API calls are performed using the httpx library. We have already developed similar service in earlier articles. You can take the code from <a href="https://github.com/chkur/clustering_example_for_article/tree/article5">GitHub</a> and check out the brancharticle5 to work on the tasks in this article. I have added an Nginx container, some code, views and settings here. You need to get the latest code and run the following commands to start the project and fill the database with data (it will take some time):</p><pre>git clone https://github.com/chkur/clustering_example_for_article.git<br>git checkout article5<br>docker-compose up --build</pre><p>And now in another console:</p><pre>docker-compose exec web python manage.py import_rows</pre><p>Open <a href="http://localhost/api/doc/swagger/">http://localhost/api/doc/swagger/</a> in your browser to access Swagger. Here, you can send requests to the service.</p><p>We will modify the timeout settings in the environment sections of the docker-compose.yml file. Look for NGINX_TIMEOUT, POSTGRES_TIMEOUT, HTTPX_TIMEOUT, LONG_API_DURATION, and GUNICORN_TIMEOUT settings. Keep in mind that each service or library has its default timeout value. For Nginx’s proxy_read_timeout, it is 60 seconds; for PostgreSQL’s statement_timeout, it’s 0 (no timeout value); for Gunicorn, it’s 30 seconds; and for httpx, the default timeout value is None (no timeout value). Initially, we set a zero value for PostgreSQL and 600 seconds for other services to ensure a successful response. We will be working with POST-requests on the /api/vehicles/js_clustering/ and /api/vehicles/map/ endpoints. Later, we will see the differences between them. It is not important which request body we send to these endpoints.</p><p>Now, let’s trace our query’s path through the service. It originates from the user’s browser, passes through Nginx, which redirects it to the Gunicorn service. Within the Gunicorn service, our Django app code executes database calls and external API requests via httpx. Finally, a new record needs to be written to the database, and we must return successfull response to the user. I added endpoints for testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I8mG-TWfK8dx0sO9zPdcQ.png" /></figure><p>Open the docker-compose.yml file and check the settings:</p><pre>NGINX_TIMEOUT=600<br>POSTGRES_TIMEOUT=0<br>HTTPX_TIMEOUT=600<br>GUNICORN_TIMEOUT=600<br>LONG_API_DURATION=30</pre><p>Restart docker-compose and send a POST request to <a href="http://localhost/api/doc/swagger/">http://localhost/api/doc/swagger/</a> with any request body. Wait for the result:</p><pre>{<br>  &quot;name&quot;: &quot;POST result&quot;,<br>  &quot;text&quot;: &quot;260557 items in the queryset, external API response status is 200&quot;<br>}</pre><p>Now we can see that there are no problems with the endpoint. However, let’s explore some unusual configuration examples here. It’s crucial to understand what will happen if we forget about correct system configurations.</p><p>To begin with, let’s set a timeout in Nginx. Let’s assume that 2 seconds is a suitable value for it. Set these values in docker-compose.yml file:</p><pre>NGINX_TIMEOUT=2<br>POSTGRES_TIMEOUT=0<br>HTTPX_TIMEOUT=600<br>GUNICORN_TIMEOUT=600<br>LONG_API_DURATION=30</pre><p>And restart docker-compose. Run a POST request to <a href="http://localhost/api/vehicles/js_clustering/">http://localhost/api/vehicles/js_clustering/</a>. Since our request lasts more than 2 seconds, the user will receive an error response with a 504 code, which is the correct code for this scenario. However, the request will continue to execute in the Gunicorn process, where the timeout value is larger. You may run this command:</p><pre>docker-compose exec web python manage.py shell</pre><p>And then, watch for the last created Comment object (it has to be created on our endpoint) before running the query and, later, a couple of minutes after getting a 504 error:</p><pre>from main.models import Comment<br>Comment.objects.last()</pre><p>We will observe that after some time, a new Comment object will be created. If it were a payment endpoint, a user could receive an error and attempt to make the payment again. Moreover, our server will be under load during this time, providing no benefit from such a configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VucV0OCCtY-zlubA87xe_A.png" /></figure><p>Let’s conduct an experiment: remove the timeout value in Nginx and instead, add a 10-second timeout value to the Gunicorn service:</p><pre>NGINX_TIMEOUT=600<br>POSTGRES_TIMEOUT=0<br>HTTPX_TIMEOUT=600<br>GUNICORN_TIMEOUT=10<br>LONG_API_DURATION=30</pre><p>Next, restart docker-compose and initiate a POST request to <a href="http://localhost/api/vehicles/js_clustering/">http://localhost/api/vehicles/js_clustering/</a>. The Gunicorn process will be terminated after this duration, leading to a 502 error for the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtRMbqsiMH9YEui3qTrFYw.png" /></figure><p>The current error code is not suitable; therefore, we will set identical timeout values (10 seconds) for both Nginx and Gunicorn:</p><pre>NGINX_TIMEOUT=10<br>POSTGRES_TIMEOUT=0<br>HTTPX_TIMEOUT=600<br>GUNICORN_TIMEOUT=10<br>LONG_API_DURATION=30</pre><p>After restarting docker-compose, initiate a POST request to <a href="http://localhost/api/vehicles/js_clustering/">http://localhost/api/vehicles/js_clustering/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uVLVWPQHFVvpQcJJ1HbyTw.png" /></figure><p>We now receive the correct 504 error code, but what happens with our request? According to the diagram above, we assumed there was an issue with another API call, causing it to take too long, resulting in nothing being written to the database. In such a scenario, the user would receive an error, which would be appropriate. However, we’re not entirely certain. Let’s update our timeout configuration as follows:</p><pre>NGINX_TIMEOUT=10<br>POSTGRES_TIMEOUT=0<br>HTTPX_TIMEOUT=2<br>GUNICORN_TIMEOUT=10<br>LONG_API_DURATION=1</pre><p>Here, we will change LONG_API_DURATION to a shorter value. Now, the Gunicorn process will be terminated when a long query to PostgreSQL is being executed. In this situation, there are two possible options. For general queries, the database query will be terminated upon client connection loss. We can observe this in our request to <a href="http://localhost/api/vehicles/js_clustering/">http://localhost/api/vehicles/js_clustering/</a>, where we have an ordinary SELECT query with a substantial amount of data. We can open the process manager and check the PostgreSQL processes. Before the Gunicorn process is terminated, we can see the SELECT process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZRhUqoYHm7nDmgMx9-qUg.png" /></figure><p>When the Gunicorn process is terminated due to a timeout, we observe that the corresponding PostgreSQL process is also terminated. The diagram illustrates this process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JLw6MXYXgQjnhVerni2lA.png" /></figure><p>However, in some cases, a complex database query continues even after the Gunicorn process has been terminated. For example, a PostGIS query with the ST_ClusterDBScan function does not terminate upon client disconnect. Run a POST request on the <a href="http://localhost/api/vehicles/map/">http://localhost/api/vehicles/map/</a> endpoint and wait for a 504 response. Then, check the docker-compose console to confirm that the Gunicorn process was terminated as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GE3iT1lDeuz351xDN66GYA.png" /></figure><p>However, in the process manager, we observe that the SELECT query is still running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSiA9_0f2W9sOJco6IHgfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpH5s47nkBNTrzBsZxhCLQ.png" /></figure><p>If it were an INSERT query, we could receive a 504 response but still write some data to the database. Also in such a situation the server would be burdened with database queries for rejected user requests.</p><p>Here, we need to configure our PostgreSQL and set its statement_timeout to a reasonable value. We have decided that 0.5 seconds will be sufficient for database query execution. Below are our new timeout settings; please ensure that PostgreSQL timeout settings are in milliseconds:</p><pre>NGINX_TIMEOUT=600<br>POSTGRES_TIMEOUT=500<br>HTTPX_TIMEOUT=2<br>GUNICORN_TIMEOUT=600<br>LONG_API_DURATION=1</pre><p>Now, if the database query takes too long, we will receive an error in PostgreSQL like this:</p><pre>canceling statement due to statement timeout</pre><p>Additionally, it’s important to note that this timeout value will be applied to any database query. If we have queries that take a long time to execute, they will no longer function. Therefore, we need to be cautious when setting the timeout value here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5P-YnLGczD_S5mvbOysJ3Q.png" /></figure><p>In such case it may be good choice to set up database replication, where main database will handle current fast queries, and we will have database replica for heavy queries which can last quite a long time. But if we have no resources to do this — we have to set up statement_timeout to the maximum reasonable value for all our project.</p><p>We may encounter issues with external API calls. The external API may be unavailable or overloaded. Let’s set timeout values:</p><pre>NGINX_TIMEOUT=600<br>POSTGRES_TIMEOUT=0<br>HTTPX_TIMEOUT=1<br>GUNICORN_TIMEOUT=600<br>LONG_API_DURATION=20</pre><p>We will receive a 500 error here because we haven’t handled exceptions for httpx errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMg_DWaGyXs8R3t86lIh9A.png" /></figure><p>While handling the exception is important, the main challenge lies in understanding the outcomes of the external API endpoint. There is no one-size-fits-all solution, but we need to consider two key factors: Does the external API define timeout values, and is it critical for our service to wait for a response?</p><p>If the external API has defined timeout values that are acceptable for our service, we should align our library API calls (using httpx in our case) with these external API timeout values. On the other hand, if the timeout value is excessive or undefined for our service, we must decide the action to take when cutting the connection before receiving a response. For instance, if the external API for message checking has a 600-second timeout, and waiting for such a duration is not acceptable for our service, we might set a shorter timeout (e.g., 5 seconds) in the httpx call and return an error response to the end user.</p><p>In certain cases, we might choose to ignore external API unavailability, logging the issues without affecting the end user. However, for critical processes like a payment system with a bank API timeout of 600 seconds, it might be more prudent to wait for the full duration before returning an error to the end user.</p><p>It’s clear that in one project we have critical and non-critical endpoints, simple and heavy database queries etc. If we have just one endpoint we must wait 600 seconds, that does not mean that we have to wait 600 seconds for any endpoint before killing its process. We already considered what we can do for database queries — use replication and choose database for query executing. In Django we can use database routers or specify database for specific query manually. In app service like Gunicorn we can’t set different timeouts for different endpoints, so we should deploy several Gunicorn services with different timeout settings. In nginx we should setup routing for those Gunicorn services, and set up different timeouts for each of them.</p><p>Apologies if you didn’t find answers here to the question of optimal project configuration — it varies based on individual tasks and resources. However, I hope this article emphasizes the importance of correctly configuring timeout settings during your service deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bb9d9445fa" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/bad-advice-for-a-developer-dont-consider-timeouts-let-the-user-be-surprised-4bb9d9445fa">Bad advice for a developer: don’t consider timeouts; let the user be surprised</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Manage Django Model in Another Database Without Database Routers]]></title>
            <link>https://medium.com/better-programming/how-to-manage-django-model-in-another-database-without-database-routers-e6dbeae401c9?source=rss-998425d33551------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6dbeae401c9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Sergey Bachurin]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 18:39:31 GMT</pubDate>
            <atom:updated>2023-03-06T18:39:31.769Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick ’n’ dirty way</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ri1DDuq1R8zp5--FS6MRMw.jpeg" /><figcaption>Django database models on two computers and a cat on the table (DeepAI)</figcaption></figure><p>Often, we need to store data that is not related to the main functionality of the application. This may include logs, historical data, comments, and so on. This data often grows and becomes redundant in the main database, slowing backup creation, restoration, and queries. At this point, you may realize that this data should have been stored in a separate database, as the relations to the main table are rarely used and not crucial to the project. By moving this data to a different database, everyone can benefit.</p><p>Backups for the main database will be faster, and you can transfer the second database to another server and offload resources for queries of the main database. While setting up database replication is also an option, this article does not cover that topic. The solution described in this article is suitable for small projects that have unexpectedly accumulated a large amount of data.</p><p>Create a Django project with such models (you can get project code <a href="https://github.com/chkur/garbage_models">here</a>. To check out the commit with one database only, run git checkout mono_db):</p><pre>from django.db import models<br><br><br>class Category(models.Model):<br>    name = models.CharField(<br>        max_length=100,<br>    )<br><br><br>class Product(models.Model):<br>    name = models.CharField(<br>        max_length=1024,<br>    )<br>    price = models.DecimalField(<br>        max_digits=7,<br>        decimal_places=2,<br>    )<br>    category = models.ForeignKey(<br>        &quot;Category&quot;,<br>        on_delete=models.PROTECT,<br>    )<br><br><br>class Selling(models.Model):<br>    product = models.ForeignKey(<br>        &quot;Product&quot;,<br>        on_delete=models.CASCADE,<br>    )<br>    dt = models.DateTimeField(<br>        auto_now_add=True,<br>    )<br>    quantity = models.IntegerField(<br>        default=1,<br>    )<br>    order_data = models.JSONField(<br>        default=dict,<br>    )</pre><p>We have the Selling model containing product sales data, which we want to remove from the default database. However, we need to fill the tables with some data before doing so.</p><pre>python manage.py fake_records</pre><p>It will run simple management commands like the following:</p><pre>import random<br><br>from django.core.management import BaseCommand<br><br>from main.models import Category, Product, Selling<br><br><br>class Command(BaseCommand):<br>    def handle(self, *args, **kwargs):<br>        cat1, _ = Category.objects.get_or_create(name=&quot;Common&quot;)<br>        cat2, _ = Category.objects.get_or_create(name=&quot;Custom&quot;)<br>        for i in range(1, 1001):<br>            product = Product.objects.create(<br>                category=random.choice([cat1, cat2]),<br>                price=random.choice([100, 1000, 2000, 500]),<br>                name=f&quot;Product #{i}&quot;,<br>            )<br>            print(f&quot;\rCreated new product &#39;{product}&#39;, {i} of 1000&quot;, end=&quot;&quot;)<br>            for sell_num in range(random.randint(1, 10)):<br>                Selling.objects.create(<br>                    product=product,<br>                    quantity=random.randint(1, 5),<br>                    order_data={<br>                        &quot;customer&quot;: f&quot;Customer {sell_num}&quot;,<br>                        &quot;paid&quot;: random.choice([&quot;CARD&quot;, &quot;CASH &quot;]),<br>                    },<br>                )</pre><p>Now we will add a second database to the settings:</p><pre>DATABASES = {<br>    &quot;default&quot;: {<br>        &quot;ENGINE&quot;: &quot;django.db.backends.postgresql&quot;,<br>        &quot;NAME&quot;: &quot;example_db&quot;,<br>        &quot;USER&quot;: &quot;some_user&quot;,<br>        &quot;PASSWORD&quot;: &quot;POSTGRES_PASSWORD&quot;,<br>        &quot;HOST&quot;: &quot;db&quot;,<br>        &quot;PORT&quot;: 5432,<br>    },<br>    &quot;garbage&quot;: {<br>        &quot;ENGINE&quot;: &quot;django.db.backends.postgresql&quot;,<br>        &quot;NAME&quot;: &quot;garbage_db&quot;,<br>        &quot;USER&quot;: &quot;some_user&quot;,<br>        &quot;PASSWORD&quot;: &quot;POSTGRES_PASSWORD&quot;,<br>        &quot;HOST&quot;: &quot;db&quot;,<br>        &quot;PORT&quot;: 5432,<br>    },<br>}</pre><p>The next step for any normal developer is to read the documentation and define <a href="https://docs.djangoproject.com/en/4.1/topics/db/multi-db/#topics-db-multi-db-routing">database routers</a> for the project. However, we won’t do that. Instead, we will create a custom manager and a custom base abstract model like this:</p><pre>class GarbageManager(models.Manager):<br>    def get_queryset(self):<br>        return models.QuerySet(self.model, using=&quot;garbage&quot;)</pre><pre>class GarbageModel(models.Model):<br>    objects = GarbageManager()<br><br>    class Meta:<br>        abstract = True<br><br>    def save(<br>        self,<br>        force_insert=False,<br>        force_update=False,<br>        using=&quot;garbage&quot;,<br>        update_fields=None,<br>    ):<br>        return super().save(<br>            force_insert=force_insert,<br>            force_update=force_update,<br>            using=using,<br>            update_fields=update_fields,<br>        )<br><br>    def delete(self, using=&quot;garbage&quot;, keep_parents=False):<br>        return super().delete(<br>            using,<br>            keep_parents,<br>        )</pre><p>The next step is to inherit the Selling model from the GarbageModel. However, we have a field called product, which is a foreign key to the Product model. Since the Product model will be stored in the default database, we need to remove the constraint for this field. We can do this using Django ORM migrations by changing the field description.</p><pre>class Selling(GarbageModel):<br>    product = models.ForeignKey(<br>        &quot;Product&quot;,<br>        db_index=True,<br>        db_constraint=False,<br>        on_delete=models.DO_NOTHING,<br>    )<br>    # Other fields are unchanged...</pre><p>You need to migrate if you have created a new model and have no data in the table. But we have existing data in the table. Create an auto-migration, but don’t migrate yet. We need to move our existing data for the Selling model from the default database to the garbage database. We can do it with this migration but we must add some actions. I recommend renaming the migration file in such cases to note that there were some non-ordinary actions. I renamed it to 0003_MOVE_SALES.py. We will add data copying here. Create one more management command called move_sales:</p><pre>from django.core.management import BaseCommand<br><br>from main.models import Selling<br><br>from django.db import transaction<br><br><br>class Command(BaseCommand):<br>    def handle(self, *args, **kwargs):<br>        with transaction.atomic():<br>            if Selling.objects.order_by(&quot;id&quot;).using(&quot;garbage&quot;).exists():<br>                return<br><br>            old_records = Selling.objects.order_by(&quot;id&quot;).using(&quot;default&quot;)<br>            new_db_data = []<br>            for data_default in old_records:<br>                old_data_item = {<br>                    k: v<br>                    for k, v in data_default.__dict__.items()<br>                    if not k.startswith(&quot;_&quot;)<br>                }<br>                new_db_data.append(Selling(**old_data_item))<br><br>            Selling.objects.bulk_create(new_db_data, batch_size=5000)</pre><blockquote>For really large amounts of data, this approach may not be the best. You should consider other methods for migrating your data, such as exporting it to an external file or using database replication.</blockquote><p>We need to check whether the data exists in the garbage database because we will run the migration twice, once on the default database, and once on the garbage database.</p><p>We will now add the code to run move_sales management command to our migration file:</p><pre>from django.db import migrations, models<br>import django.db.models.deletion<br>from django.core.management import call_command<br><br><br>def copy_data(apps, schema_editor):<br>    call_command(&quot;move_sales&quot;)<br><br><br>class Migration(migrations.Migration):<br>    dependencies = [<br>        (&quot;main&quot;, &quot;0002_selling_order_data&quot;),<br>    ]<br><br>    operations = [<br>        migrations.AlterField(<br>            model_name=&quot;selling&quot;,<br>            name=&quot;product&quot;,<br>            field=models.ForeignKey(<br>                db_constraint=False,<br>                on_delete=django.db.models.deletion.DO_NOTHING,<br>                to=&quot;main.product&quot;,<br>            ),<br>        ),<br>        migrations.RunPython(copy_data, migrations.RunPython.noop),<br>    ]</pre><p>Now we can run the migrations, first on the garbage database, and then on the default database. We need to run the migrations in this order because the first operation in this migration removes the table constraint for the foreign key. If we don’t remove it, we won’t be able to create Selling records in the garbage database because the table for the Product model in the garbage database is empty.</p><pre>docker-compose exec web python manage.py migrate --database garbage<br>docker-compose exec web python manage.py migrate</pre><p>Looks good, but let’s go to the shell and watch the data:</p><pre>&gt;&gt;&gt; Selling.objects.using(&quot;garbage&quot;).all()<br>&lt;QuerySet [&lt;Selling: Selling object (1)&gt;, &lt;Selling: Selling object (2)&gt;, &lt;Selling: Selling object (3)&gt;, &lt;Selling: Selling object (4)&gt;, &lt;Selling: Selling object (5)&gt;, &lt;Selling: Selling object (6)&gt;, &lt;Selling: Selling object (7)&gt;, &lt;Selling: Selling object (8)&gt;, &lt;Selling: Selling object (9)&gt;, &lt;Selling: Selling object (10)&gt;, &lt;Selling: Selling object (11)&gt;, &lt;Selling: Selling object (12)&gt;, &lt;Selling: Selling object (13)&gt;, &lt;Selling: Selling object (14)&gt;, &lt;Selling: Selling object (15)&gt;, &lt;Selling: Selling object (16)&gt;, &lt;Selling: Selling object (17)&gt;, &lt;Selling: Selling object (18)&gt;, &lt;Selling: Selling object (19)&gt;, &lt;Selling: Selling object (20)&gt;, &#39;...(remaining elements truncated)...&#39;]&gt;</pre><p>Now we will check that, by default, we are getting records for the Selling model from the garbage database, while Product records are still being retrieved from the default database:</p><pre>&gt;&gt;&gt; Product.objects.all().db<br>&#39;default&#39;<br>&gt;&gt;&gt; Selling.objects.all().db<br>&#39;garbage&#39;</pre><p>We have successfully retrieved records from the desired database. However, there is an issue. We have encountered two problems. Firstly, the dt field, which has auto_now_add=true, has been broken, as Django ignored the dt values in our data.</p><pre>&gt;&gt;&gt; Selling.objects.using(&quot;default&quot;).first().dt<br>datetime.datetime(2020, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)<br>&gt;&gt;&gt; Selling.objects.using(&quot;garbage&quot;).first().dt<br>datetime.datetime(2023, 2, 28, 11, 1, 59, 871095, tzinfo=datetime.timezone.utc)</pre><p>Secondly, there is an issue with creating new Selling records.</p><pre>&gt;&gt;&gt; Selling.objects.create(product_id=1, quantity=2)<br>Traceback (most recent call last):<br>  File &quot;/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py&quot;, line 89, in _execute<br>    return self.cursor.execute(sql, params)<br>           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint &quot;main_selling_pkey&quot;<br>DETAIL:  Key (id)=(1) already exists.</pre><p>We need to correct the sequence value for the Selling.id field.</p><p>We will delete all Selling records from the garbage database and rewrite the migration.</p><p>To fix the sequence, we need to add a new migration operation:</p><pre>        migrations.RunSQL(<br>            &quot;&quot;&quot;<br>            SELECT setval(&#39;main_selling_id_seq&#39;, max(id)) FROM main_selling;<br>            &quot;&quot;&quot;,<br>            migrations.RunSQL.noop,<br>        ),</pre><p>What about the dt field? We shouldn’t use auto_now_add here. Instead, we should set default argument to timezone.now. If we don’t do this, any value for dt will be replaced with the current time even if we passed our value.</p><pre>    dt = models.DateTimeField(<br>        default=timezone.now,<br>    )</pre><p>Now, we need to delete the Selling data from garbage database, migrate databases to the previous migration, and apply our migration again.</p><pre>&gt;&gt;&gt; Selling.objects.all().delete()<br>(5450, {&#39;main.Selling&#39;: 5450})<br><br>python manage.py migrate main 0002<br>python manage.py migrate main 0002 --database garbage<br>python manage.py migrate --database garbage<br>python manage.py migrate</pre><p>Later, when we will be sure about our Selling data in the new database, we can delete Selling data from the default database.</p><pre>&gt;&gt;&gt; Selling.objects.all().using(&quot;default&quot;).delete()<br>(5450, {&#39;main.Selling&#39;: 5450})</pre><p>At last, let’s check Django admin panel. We need to define __str__ methods for our models. Describe your models in the admin.py file:</p><pre>from django.contrib import admin<br><br>from main.models import Product, Selling<br><br><br>class SellingInline(admin.TabularInline):<br>    model = Selling<br>    readonly_fields = [&quot;dt&quot;, &quot;quantity&quot;, &quot;order_data&quot;]<br>    ordering = [&quot;-dt&quot;]<br>    extra = 0<br>    can_delete = False<br>    show_change_link = False<br><br>    def has_add_permission(self, request, obj):<br>        return False<br><br><br>@admin.register(Product)<br>class OrderRequestAdmin(admin.ModelAdmin):<br>    inlines = [<br>        SellingInline,<br>    ]</pre><p>Create a superuser and go to <a href="http://localhost:8000/admin/">http://localhost:8000/admin/</a>. Open any product and verify if all Selling items from the garbage database are visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nvTEiyzSPO2R38Y1Nwh1g.png" /></figure><p>Now all data for the Selling model will be saved to the garbage database and will be requested from the garbage database as well. Admin site works as expected. The structure in both databases is identical. It’s clear that we now have some restrictions for the Product and Selling models. We can’t use them in the same Django ORM queryset since they belong to different databases. If we need to get sales data for specific products, we need to get their IDs from the default database and then request data for those IDs from the garbage database. For more complex raw SQL queries, we can use the PostgreSQL module dblink.</p><p>Code for this article can be found at:</p><p>Before database splitting <a href="https://github.com/chkur/garbage_models/tree/mono_db">https://github.com/chkur/garbage_models/tree/mono_db</a></p><p>After database splitting <a href="https://github.com/chkur/garbage_models/tree/master">https://github.com/chkur/garbage_models/tree/master</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6dbeae401c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-manage-django-model-in-another-database-without-database-routers-e6dbeae401c9">How To Manage Django Model in Another Database Without Database Routers</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partitioning in Django+PostgreSQL]]></title>
            <link>https://medium.com/better-programming/partitioning-in-django-postgresql-d7ebbe8f9c2b?source=rss-998425d33551------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7ebbe8f9c2b</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[partitioning]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Sergey Bachurin]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 18:21:30 GMT</pubDate>
            <atom:updated>2023-02-24T20:29:58.853Z</atom:updated>
            <content:encoded><![CDATA[<h3>Partitioning in Django + PostgreSQL</h3><h4>Manually create partitioned tables in the existing project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Y9IwnPyhvYLOc2M6ZveAmw.jpeg" /><figcaption>That’s how DeepAI imagines “Database partitioning”</figcaption></figure><p>We have a <a href="https://github.com/chkur/clustering_example_for_article/tree/article3">test project</a> with a single model Vehicle that contains some data about abandoned cars in Chicago (we already experimented with it in previous articles <a href="https://medium.com/better-programming/geoclustering-in-django-project-ba0c0511e3dd">1</a> and <a href="https://medium.com/@bachurin.sn/79111a1de334">2</a>). In the README file, you can find how to run the project and fill the Vehicle model with the test data.</p><p>Let’s imagine our test project is growing. We will add some new models, relationships, and inherited models. As you understand, that will make our task more complex and interesting than working with a standalone model.</p><p>In the table Vehicle, we will add a field named responsible , which will be the foreign key to the new model Responsible, and the new model Reporter with m2m relationship:</p><pre>class Vehicle(models.Model):<br><br>    # Some text, numeric or date fields...<br><br>    # Now add a foreign key:<br>    responsible = models.ForeignKey(<br>        &quot;Responsible&quot;,<br>        null=True,<br>        on_delete=models.SET_NULL,<br>    )<br><br>class Person(models.Model):<br>    name = models.CharField(max_length=255)<br>    phone = models.CharField(max_length=50)<br><br>    class Meta:<br>        abstract = True<br><br><br>class Responsible(Person):<br>    ...<br><br><br>class Reporter(Person):<br>    reports = models.ManyToManyField(<br>        &quot;Vehicle&quot;,<br>        related_name=&quot;reporters&quot;,<br>    )</pre><p>Also, we will keep some additional data for different cases in the new inherited models. In this case, we will create a one-to-one relation with the column vehicle_ptr_id in the inherited model, which will be related to id field in the Vehicle model:</p><pre>class CriminalVehicle(Vehicle):<br>    top_secret = models.BooleanField(default=False)<br>    police_data = models.JSONField(default=dict)<br><br><br>class MistakeVehicle(Vehicle):<br>    description = models.TextField()<br><br><br>class RepeatedVehicle(Vehicle):<br>    previous_event = models.OneToOneField(<br>        &quot;Vehicle&quot;,<br>        related_name=&quot;next_event&quot;,<br>        on_delete=models.PROTECT,<br>    )</pre><p>We will create some new management commands to generate some fake data for the project:</p><pre>docker-compose exec web python manage.py create_mistake_vehicles<br>docker-compose exec web python manage.py create_criminal_vehicles<br>docker-compose exec web python manage.py create_repeated_vehicles<br>docker-compose exec web python manage.py create_responsible_and_reporters</pre><p>For repeat cases, there will be vehicles with the same vehicle_make and vehicle_color repeated from 2 to 5 times:</p><pre>from django.db.utils import IntegrityError<br>from django.contrib.postgres import aggregates<br>from django.core.management import BaseCommand<br>from django.db.models import Count<br><br>from main.models import Vehicle, RepeatedVehicle<br><br><br>class Command(BaseCommand):<br>    def handle(self, *args, **options):<br>        # Assume that vehicles with the same color and manufacturer<br>        # which are repeated from 2 to 5 times are &quot;RepeatedVehicle&quot;<br>        repeated_vehicles = (<br>            Vehicle.objects.values(&quot;vehicle_make&quot;, &quot;vehicle_color&quot;)<br>            .annotate(<br>                count=Count(&quot;id&quot;),<br>                ids=aggregates.ArrayAgg(&quot;id&quot;),<br>            )<br>            .filter(count__range=[2, 5])<br>        )<br>        for global_num, item in enumerate(repeated_vehicles, 1):<br>            for num, item_id in enumerate(item[&quot;ids&quot;][1:], 1):<br>                vehicle = Vehicle.objects.get(id=item_id)<br>                vehicle.__class__ = RepeatedVehicle<br>                vehicle.vehicle_ptr_id = item_id<br>                vehicle.previous_event_id = item[&quot;ids&quot;][num - 1]<br><br>                try:<br>                    vehicle.save()<br>                except IntegrityError:<br>                    # if already exist<br>                    pass<br>                print(<br>                    f&quot;Create repeated vehicle {global_num} of {len(repeated_vehicles)}&quot;<br>                )</pre><p>Responsible, reporters, “criminal,” and “mistake” cases will be created randomly. That code has nothing interesting for us. For random texts and phones, let’s use <a href="https://github.com/joke2k/faker">faker</a>.</p><p>Also, using some applications to select additional data for queries will be more convenient. So, if you query vehicles — for every “criminal,” “mistake,” or “repeated” case, you may want to get its own subclass. For this, we can use Django apps like <a href="https://github.com/jazzband/django-model-utils">django-model-utils</a> or <a href="https://github.com/django-polymorphic/django-polymorphic">django-polymorphic</a>. I’ll choose django-model-utils.</p><p>So, our project has been growing for some time and has accumulated a large amount of data with some relations. Also, we added third-party apps, which can make our work with the database more complicated. They add their own managers, or even their own tables, etc. And some days, we have noticed that queries take significantly longer to complete. We won’t discuss why partitioning may help you in this case — you can read it in the <a href="https://www.postgresql.org/docs/current/ddl-partitioning.html">official PostgreSQL documentation</a>. We will try to implement partitioning in our Django project.</p><h3>Django Applications for Partitioning</h3><p>If you’ve read PostgreSQL documentation, you know there are two types of partitioning — declarative partitioning and partitioning using inheritance. And two actual Django applications handle table partitioning —<a href="https://github.com/maxtepkeev/architect"> architect</a> and <a href="https://github.com/SectorLabs/django-postgres-extra">django-postgres-extra</a>. Architect implements partitioning using inheritance, while django-postgres-extra works with declarative partitioning.</p><p>Architect uses triggers for creating new partitions — you don’t have to care about it. But there are problems with constraints on foreign keys and table modifications on Django migrations. Also, the architect project has not been updated for a long time.</p><p>django-postgres-extra, on the other side, has its pros and cons. It looks easy to use — you need to add some lines to your model code. But also, it uses its own manager, its own migration commands, and its own database engine. And in our case, it seems it doesn’t work with models inheritance. Anyway, you can try to use this application in your project. Maybe it will be enough for your needs.</p><p>And last but not least, the reason is — it will be boring to write an article about simply using third-side apps. So we will start implementing partitioning ourselves. It’s not too hard; in most cases, it is enough to do it once.</p><h3>Preparing</h3><p>First and most trivial — you need to have backups of your database and some fast way to restore your database from backup. You will break your database several times before your migration will work successfully.</p><p>Get the database copy with the needed structure. It will be better to get it from the production server. Ideally, with the same amount of data. But if it’s too large — you can always get the database structure running pg_dump with --schema-only key and then fill it with some test data.</p><p>The main problem is to define a key for partitioning. It depends on which queries will mostly use your project. We will assume we won’t have specific often-used filters on dates, status, etc. So, it will be correct to split our table by field id. It’s a simple option because it doesn’t need to create complex primary or foreign keys. I usually create partitions with sizes of about 100k records.</p><p>We will create partitions on tables main_vehicle, main_criminalvehicle and main_comment. We need to get DDL statements for them. Here’s how to do that:</p><pre>docker-compose exec db pg_dump -Ugeo -t &#39;main_vehicle&#39; --schema-only clustering_example<br>docker-compose exec db pg_dump -Ugeo -t &#39;main_criminalvehicle&#39; --schema-only clustering_example<br>docker-compose exec db pg_dump -Ugeo -t &#39;main_comment&#39; --schema-only clustering_example</pre><p>We’ll need a list of foreign key constraints for the partitioning table. We will remove them before recreating the table and create those constraints again after returning the data to the new partitioned table. To find foreign keys that refer to our table, we can use a query such as this:</p><pre>SELECT                                <br>    tc.table_name,<br>    tc.constraint_name,<br>    kcu.column_name,<br>    ccu.table_name AS foreign_table_name,<br>    ccu.column_name AS foreign_column_name<br>FROM <br>    information_schema.table_constraints AS tc <br>    JOIN information_schema.key_column_usage AS kcu<br>      ON tc.constraint_name = kcu.constraint_name<br>      AND tc.table_schema = kcu.table_schema<br>    JOIN information_schema.constraint_column_usage AS ccu<br>      ON ccu.constraint_name = tc.constraint_name<br>      AND ccu.table_schema = tc.table_schema<br>WHERE tc.constraint_type = &#39;FOREIGN KEY&#39; AND ccu.table_name = &#39;main_vehicle&#39;;<br>      table_name       |                         constraint_name                         |    column_name    | foreign_table_name | foreign_column_name <br>-----------------------+-----------------------------------------------------------------+-------------------+--------------------+---------------------<br> main_criminalvehicle  | main_criminalvehicle_vehicle_ptr_id_e2c1bd98_fk_main_vehicle_id | vehicle_ptr_id    | main_vehicle       | id<br> main_mistakevehicle   | main_mistakevehicle_vehicle_ptr_id_39a2a96c_fk_main_vehicle_id  | vehicle_ptr_id    | main_vehicle       | id<br> main_reporter_reports | main_reporter_reports_vehicle_id_79517bd8_fk_main_vehicle_id    | vehicle_id        | main_vehicle       | id<br> main_repeatedvehicle  | main_repeatedvehicle_vehicle_ptr_id_34a76dba_fk_main_vehicle_id | vehicle_ptr_id    | main_vehicle       | id<br> main_repeatedvehicle  | main_repeatedvehicle_previous_event_id_cf91afee_fk_main_vehi    | previous_event_id | main_vehicle       | id<br>(5 rows)</pre><p>Then we will use a template like this to drop constraints:</p><pre>ALTER TABLE &lt;table_name&gt;<br>    DROP CONSTRAINT &lt;constraint_name&gt;;</pre><p>And the next one to create constraints back:</p><pre>ALTER TABLE &lt;table_name&gt;<br>    ADD CONSTRAINT &lt;constraint_name&gt; FOREIGN KEY (&lt;column_name&gt;) REFERENCES &lt;foreign_table_name&gt;(&lt;foreign_column_name&gt;) DEFERRABLE INITIALLY DEFERRED;</pre><p>There is a management command in the project which will build DDL expressions to delete and create foreign keys constraints for needed tables:</p><pre>docker-compose exec web python manage.py generate_constraint_ddl</pre><p>Also, we’ll need to keep actual sequence values in the tables. In our case, we use them for primary keys only. If not, we will get errors in inserting new data later.</p><h3>Building the Migration</h3><p>Now, create new empty migration for Django:</p><pre>docker-compose exec web python manage.py makemigrations main --empty</pre><p>It will be better to rename the migration’s file to see that it’s not an auto-created migration. I named it 0005_PARTITIONING_VEHICLE.py. Look for it in our project’s repo.</p><p>Save DDL for our tables to the migration file in the new variable DDL_MIGRATE_VEHICLE. It will be the skeleton for our future table transformation. It will be better if you will create this query as a list, not just a string, so you can control the process if we get errors. Running expressions from this list looks like this:</p><pre>DDL_MIGRATE_VEHICLE = [<br>    &quot;&quot;&quot;<br>    ALTER TABLE main_criminalvehicle RENAME TO main_criminalvehicle_old;<br>    ...<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    CREATE TABLE main_criminalvehicle_1_100000 PARTITION OF main_criminalvehicle<br>        FOR VALUES FROM (1) TO (100000);<br><br>    CREATE TABLE main_criminalvehicle_100000_200000 PARTITION OF main_criminalvehicle<br>        FOR VALUES FROM (100000) TO (200000);<br>    ...<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    INSERT INTO main_criminalvehicle SELECT * FROM main_criminalvehicle_old;<br>    DROP TABLE main_criminalvehicle_old;<br>    &quot;&quot;&quot;,<br>    # ...<br>]<br># ...<br>class Migration(migrations.Migration):<br>    # ...<br>    operations = [migrations.RunSQL(i) for i in DDL_MIGRATE_VEHICLE]</pre><p>Now we need to modify this SQL to create the correct partitioned table and to save old data stored in the table. And our strategy for table partitioning will include the following steps:</p><ol><li>Remove “ONLY ” in our DDL script. We don’t need it for our partitioned table</li><li>Drop foreign keys constraints in the tables which have relations to the partitioned table</li><li>Rename old table</li><li>Rename sequences for old table (or just delete them)</li><li>Drop the primary key for the old table</li><li>Create a new partitioned table</li><li>Create partitions for all existing data and some data in the future</li><li>Insert data from the old table to the new one</li><li>Drop the old table</li><li>Alter sequence for id field to generate correct id values (we can use the value from the old sequence to get the maximum value for the id column)</li><li>Create indexes</li><li>Create foreign keys constraints in the tables which have relations to the partitioned table</li></ol><p>For the table, main_comment, it will have some differences. We’ll create a complex primary key because it should contain a partition key column. As we partitioned the table, main_comment, on column vehicle_id — the primary key consists of columns vehicle_id and id .</p><pre>    ALTER TABLE public.main_comment<br>        ADD CONSTRAINT main_comment_pkey PRIMARY KEY (vehicle_id, id);</pre><p>And for the table main_criminalvehicle we will not create any sequence because its primary key is one-to-one relation to the id column of the table main_vehicle.</p><p>Full migration’s code now is:</p><pre>from django.db import migrations<br><br>DDL_MIGRATE_VEHICLE = [<br>    &quot;&quot;&quot;<br>    ALTER TABLE main_criminalvehicle RENAME TO main_criminalvehicle_old;<br>    ALTER TABLE public.main_criminalvehicle_old<br>        DROP CONSTRAINT main_criminalvehicle_pkey;<br>    CREATE TABLE public.main_criminalvehicle (<br>        vehicle_ptr_id bigint NOT NULL,<br>        top_secret boolean NOT NULL,<br>        police_data jsonb NOT NULL<br>    ) PARTITION BY RANGE(vehicle_ptr_id);<br>    ALTER TABLE public.main_criminalvehicle OWNER TO geo;<br>    ALTER TABLE public.main_criminalvehicle<br>        ADD CONSTRAINT main_criminalvehicle_pkey PRIMARY KEY (vehicle_ptr_id);<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    CREATE TABLE main_criminalvehicle_1_100000 PARTITION OF main_criminalvehicle<br>        FOR VALUES FROM (1) TO (100000);<br>    CREATE TABLE main_criminalvehicle_100000_200000 PARTITION OF main_criminalvehicle<br>        FOR VALUES FROM (100000) TO (200000);<br>    CREATE TABLE main_criminalvehicle_200000_300000 PARTITION OF main_criminalvehicle<br>        FOR VALUES FROM (200000) TO (300000);<br>    CREATE TABLE main_criminalvehicle_300000_400000 PARTITION OF main_criminalvehicle<br>        FOR VALUES FROM (300000) TO (400000);<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    INSERT INTO main_criminalvehicle SELECT * FROM main_criminalvehicle_old;<br>    DROP TABLE main_criminalvehicle_old;<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE main_criminalvehicle<br>        DROP CONSTRAINT IF EXISTS main_criminalvehicle_vehicle_ptr_id_e2c1bd98_fk_main_vehicle_id;<br>    ALTER TABLE main_mistakevehicle<br>        DROP CONSTRAINT IF EXISTS main_mistakevehicle_vehicle_ptr_id_39a2a96c_fk_main_vehicle_id;<br>    ALTER TABLE main_reporter_reports<br>        DROP CONSTRAINT IF EXISTS main_reporter_reports_vehicle_id_79517bd8_fk_main_vehicle_id;<br>    ALTER TABLE main_repeatedvehicle<br>        DROP CONSTRAINT IF EXISTS main_repeatedvehicle_vehicle_ptr_id_34a76dba_fk_main_vehicle_id;<br>    ALTER TABLE main_repeatedvehicle<br>        DROP CONSTRAINT IF EXISTS main_repeatedvehicle_previous_event_id_cf91afee_fk_main_vehi;<br>    ALTER TABLE main_comment<br>        DROP CONSTRAINT main_comment_vehicle_id_4709556a_fk_main_vehicle_id;<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE public.main_vehicle<br>        DROP CONSTRAINT main_vehicle_pkey;<br>    ALTER TABLE main_vehicle RENAME TO main_vehicle_old;<br>    ALTER SEQUENCE public.main_vehicle_id_seq RENAME TO main_vehicle_id_seq_old;<br>    CREATE TABLE public.main_vehicle (<br>        id bigint NOT NULL,<br>        creation_date date NOT NULL,<br>        status character varying(20),<br>        completion_date date,<br>        service_request_number character varying(50) NOT NULL,<br>        type_of_service_request character varying(255) NOT NULL,<br>        license_plate character varying(1000),<br>        vehicle_make character varying(250),<br>        vehicle_color character varying(250),<br>        current_activity character varying(250),<br>        most_recent_action character varying(250),<br>        days_parked bigint,<br>        street_address character varying(250),<br>        zip_code character varying(10),<br>        x_coordinate double precision,<br>        y_coordinate double precision,<br>        ward integer,<br>        police_district integer,<br>        community_area integer,<br>        ssa integer,<br>        latitude double precision,<br>        longitude double precision,<br>        location public.geometry(Point,4326),<br>        responsible_id bigint<br>    ) PARTITION BY RANGE(id);<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE public.main_vehicle OWNER TO geo;<br>    ALTER TABLE public.main_vehicle ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (<br>        SEQUENCE NAME public.main_vehicle_id_seq<br>        START WITH 1<br>        INCREMENT BY 1<br>        NO MINVALUE<br>        NO MAXVALUE<br>        CACHE 1<br>    );<br>    CREATE TABLE main_vehicle_1_100000 PARTITION OF main_vehicle<br>        FOR VALUES FROM (1) TO (100000);<br>    CREATE TABLE main_vehicle_100000_200000 PARTITION OF main_vehicle<br>        FOR VALUES FROM (100000) TO (200000);<br>    CREATE TABLE main_vehicle_200000_300000 PARTITION OF main_vehicle<br>        FOR VALUES FROM (200000) TO (300000);<br>    CREATE TABLE main_vehicle_300000_400000 PARTITION OF main_vehicle<br>        FOR VALUES FROM (300000) TO (400000);<br>    INSERT INTO main_vehicle SELECT * FROM main_vehicle_old;<br>    SELECT setval(&#39;main_vehicle_id_seq&#39;, nextval(&#39;main_vehicle_id_seq_old&#39;::regclass), false);<br>    DROP TABLE main_vehicle_old;<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE public.main_vehicle<br>        ADD CONSTRAINT main_vehicle_pkey PRIMARY KEY (id);<br>    CREATE INDEX main_vehicle_completion_date_e62c3b9d ON public.main_vehicle USING btree (completion_date);<br>    CREATE INDEX main_vehicle_creation_date_41b48ffb ON public.main_vehicle USING btree (creation_date);<br>    CREATE INDEX main_vehicle_location_55ff4376_id ON public.main_vehicle USING gist (location);<br>    CREATE INDEX main_vehicle_responsible_id_cbe5a195 ON public.main_vehicle USING btree (responsible_id);<br>    CREATE INDEX main_vehicle_service_request_number_746fff87 ON public.main_vehicle USING btree (service_request_number);<br>    CREATE INDEX main_vehicle_service_request_number_746fff87_like ON public.main_vehicle USING btree (service_request_number varchar_pattern_ops);<br>    CREATE INDEX main_vehicle_vehicle_color_9bf200f6 ON public.main_vehicle USING btree (vehicle_color);<br>    CREATE INDEX main_vehicle_vehicle_color_9bf200f6_like ON public.main_vehicle USING btree (vehicle_color varchar_pattern_ops);<br>    CREATE INDEX main_vehicle_vehicle_make_28790aba ON public.main_vehicle USING btree (vehicle_make);<br>    CREATE INDEX main_vehicle_vehicle_make_28790aba_like ON public.main_vehicle USING btree (vehicle_make varchar_pattern_ops);<br>    ALTER TABLE public.main_vehicle<br>        ADD CONSTRAINT main_vehicle_responsible_id_cbe5a195_fk_main_responsible_id FOREIGN KEY (responsible_id) REFERENCES public.main_responsible(id) DEFERRABLE INITIALLY DEFERRED;<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE main_criminalvehicle<br>        ADD CONSTRAINT main_criminalvehicle_vehicle_ptr_id_e2c1bd98_fk_main_vehicle_id<br>        FOREIGN KEY (vehicle_ptr_id) REFERENCES main_vehicle(id);<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE main_mistakevehicle<br>        ADD CONSTRAINT main_mistakevehicle_vehicle_ptr_id_39a2a96c_fk_main_vehicle_id<br>        FOREIGN KEY (vehicle_ptr_id) REFERENCES main_vehicle(id);<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE main_reporter_reports<br>        ADD CONSTRAINT main_reporter_reports_vehicle_id_79517bd8_fk_main_vehicle_id<br>        FOREIGN KEY (vehicle_id) REFERENCES main_vehicle(id);<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE main_repeatedvehicle<br>        ADD CONSTRAINT main_repeatedvehicle_vehicle_ptr_id_34a76dba_fk_main_vehicle_id<br>        FOREIGN KEY (vehicle_ptr_id) REFERENCES main_vehicle(id);<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE main_repeatedvehicle<br>        ADD CONSTRAINT main_repeatedvehicle_previous_event_id_cf91afee_fk_main_vehi<br>        FOREIGN KEY (previous_event_id) REFERENCES main_vehicle(id);<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE main_comment<br>        ADD CONSTRAINT main_comment_vehicle_id_4709556a_fk_main_vehicle_id<br>        FOREIGN KEY (vehicle_id) REFERENCES main_vehicle(id);<br>    &quot;&quot;&quot;,<br>    &quot;&quot;&quot;<br>    ALTER TABLE main_comment RENAME TO main_comment_old;<br>    ALTER TABLE public.main_comment_old<br>        DROP CONSTRAINT main_comment_pkey;<br>    ALTER SEQUENCE public.main_comment_id_seq RENAME TO main_comment_id_seq_old;<br>    CREATE TABLE public.main_comment (<br>        id bigint NOT NULL,<br>        name character varying(255) NOT NULL,<br>        text text NOT NULL,<br>        vehicle_id bigint NOT NULL<br>    ) PARTITION BY RANGE(vehicle_id);<br>    ALTER TABLE public.main_comment OWNER TO geo;<br>    CREATE TABLE main_comment_1_100000 PARTITION OF main_comment<br>        FOR VALUES FROM (1) TO (100000);<br>    CREATE TABLE main_comment_100000_200000 PARTITION OF main_comment<br>        FOR VALUES FROM (100000) TO (200000);<br>    CREATE TABLE main_comment_200000_300000 PARTITION OF main_comment<br>        FOR VALUES FROM (200000) TO (300000);<br>    CREATE TABLE main_comment_300000_400000 PARTITION OF main_comment<br>        FOR VALUES FROM (300000) TO (400000);<br>    ALTER TABLE public.main_comment ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (<br>        SEQUENCE NAME public.main_comment_id_seq<br>        START WITH 1<br>        INCREMENT BY 1<br>        NO MINVALUE<br>        NO MAXVALUE<br>        CACHE 1<br>    );<br>    ALTER TABLE public.main_comment<br>        ADD CONSTRAINT main_comment_pkey PRIMARY KEY (vehicle_id, id);<br>    INSERT INTO main_comment SELECT * FROM main_comment_old;<br>    SELECT setval(&#39;main_comment_id_seq&#39;, nextval(&#39;main_comment_id_seq_old&#39;::regclass), false);<br>    DROP TABLE main_comment_old;<br>    CREATE INDEX main_comment_vehicle_id_4709556a ON public.main_comment USING btree (vehicle_id);<br>    ALTER TABLE public.main_comment<br>        ADD CONSTRAINT main_comment_vehicle_id_4709556a_fk_main_vehicle_id FOREIGN KEY (vehicle_id) REFERENCES public.main_vehicle(id) DEFERRABLE INITIALLY DEFERRED;<br>    &quot;&quot;&quot;,<br>]<br><br><br>class Migration(migrations.Migration):<br>    dependencies = [<br>        (&quot;main&quot;, &quot;0004_criminalvehicle_mistakevehicle_responsible_reporter_and_more&quot;),<br>    ]<br><br>    operations = [migrations.RunSQL(i) for i in DDL_MIGRATE_VEHICLE]</pre><h3>Create New Partitions Automatically</h3><p>With declarative partitioning, we can’t use triggers to create new partitions automatically when inserting new data if needed. That’s why we need to create a mechanism to monitor if our table has enough space for the latest data.</p><p>Create the new setting PARTITIONS_EXTRA_COUNT which will indicate how many empty partitions we need to keep. Also, we will split out our local app’s names from the INSTALLED_APPS setting to the new LOCAL_APPS setting to handle them in our script. But we should merge this list into the INSTALLED_APPS too.</p><pre>LOCAL_APPS = [<br>    &quot;main&quot;,<br>]<br><br>INSTALLED_APPS = [<br>  # Some Django&#39;s built-in and third-party apps<br>] + LOCAL_APPS</pre><p>For every partitioned table, we will create custom_partitioned attribute. It will be a dictionary that keeps data, how many records each partition will contain, and which column is the partition key. Please note that if you have inherited models, you should explicitly set this attribute for every model.</p><p>For example, for Vehicle it will look like the following:</p><pre>class Vehicle(models.Model):<br>    custom_partitioned = {<br>        &quot;column&quot;: &quot;id&quot;,<br>        &quot;size&quot;: 100000,<br>    }</pre><p>For CriminalVehicle, which is inherited from Vehicle, and should be partitioned, the code looks like this:</p><pre>class CriminalVehicle(Vehicle):<br>    custom_partitioned = {<br>        &quot;column&quot;: &quot;vehicle_ptr_id&quot;,<br>        &quot;size&quot;: 100000,<br>    }</pre><p>And for CriminalVehicle, which is inherited from Vehicle, but should not be partitioned, it looks like this:</p><pre>class MistakeVehicle(Vehicle):<br>    custom_partitioned = False</pre><p>We’ll create one more management command to check if there are enough partitions.</p><pre>from django.apps import apps<br>from django.conf import settings<br>from django.core.management import BaseCommand<br>from django.db import connection<br><br><br>class Command(BaseCommand):<br>    help = &quot;New partition generation on cron.&quot;<br><br>    def handle(self, *args, **options):<br>        # Get the last partition key value.<br>        SQL_LAST_VALUE = &quot;SELECT MAX ({column}) from {table_name}&quot;<br>        # SQL for partition creation<br>        SQL_CHECK_PARTITION = &quot;&quot;&quot;<br>            CREATE TABLE IF NOT EXISTS {table_name}_{min_value}_{max_value}<br>                PARTITION OF {table_name} FOR VALUES FROM ({min_value}) TO ({max_value});<br>        &quot;&quot;&quot;<br><br>        # Walk through the our local apps<br>        for app_name in settings.LOCAL_APPS:<br>            # Get  all models for app<br>            app_models = apps.get_app_config(app_name).get_models()<br>            # Walk through the local app models<br>            for model in app_models:<br>                # Check &quot;custom_partitioned&quot; attr. For inherited models you should set in explicitly<br>                custom_partitioned = getattr(model, &quot;custom_partitioned&quot;, None)<br>                if not custom_partitioned:<br>                    continue<br>                # Get table name in the database<br>                table_name = model._meta.db_table<br>                with connection.cursor() as cursor:<br>                    # Get current maximum for partition key<br>                    cursor.execute(<br>                        SQL_LAST_VALUE.format(<br>                            table_name=table_name,<br>                            column=custom_partitioned[&quot;column&quot;],<br>                        )<br>                    )<br>                    last_value = cursor.fetchone()[0] or 0<br><br>                    # Get partition key range for parttitions that should exist<br>                    partition_size = custom_partitioned[&quot;size&quot;]<br>                    last_partition_limit = (<br>                        last_value // partition_size * partition_size<br>                        + partition_size * settings.PARTITIONS_EXTRA_COUNT<br>                    )<br>                    partition_ranges = [<br>                        [i, i + partition_size]<br>                        for i in range(<br>                            partition_size, last_partition_limit, partition_size<br>                        )<br>                    ]<br><br>                    # Run SQL that will create partitions if they are not exist<br>                    partition_ranges.insert(0, [1, partition_size])<br>                    for partition in partition_ranges:<br>                        cursor.execute(<br>                            SQL_CHECK_PARTITION.format(<br>                                table_name=table_name,<br>                                min_value=partition[0],<br>                                max_value=partition[1],<br>                            ),<br>                            {},<br>                        )</pre><p>We can add this management command to the cron tasks to check the partition count.</p><p>Next time, we will try to move some existing table data to another database and work with it there.</p><p>Here’s the <a href="https://github.com/chkur/clustering_example_for_article">link to the GitHub repo</a>. The actual code for the article publishing date will live in the branch article3.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7ebbe8f9c2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/partitioning-in-django-postgresql-d7ebbe8f9c2b">Partitioning in Django+PostgreSQL</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customize Testing With Locust]]></title>
            <link>https://medium.com/better-programming/customize-testing-with-locust-79111a1de334?source=rss-998425d33551------2</link>
            <guid isPermaLink="false">https://medium.com/p/79111a1de334</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[locust]]></category>
            <dc:creator><![CDATA[Sergey Bachurin]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 21:51:57 GMT</pubDate>
            <atom:updated>2023-02-14T21:52:55.036Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is a continuation of the <a href="https://medium.com/@bachurin.sn/geoclustering-in-django-project-ba0c0511e3dd">article</a> where we created a simple Django project for geoclustering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ummGUQeENtnzn2Sr" /><figcaption>Photo by <a href="https://unsplash.com/@geojango_maps?utm_source=medium&amp;utm_medium=referral">GeoJango Maps</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>The code examples in this article are often truncated, so it will be better to go to the <a href="https://github.com/chkur/clustering_example_for_article">project’s GitHub page</a> and load the project to review. I created branch article2 where will live actual code for the article publishing date.</blockquote><p>Our task is to check if the project stays alive with a few active users online.</p><p>We will create simple load tests for our code. For this stage, we don’t expect many users on the site simultaneously, but we have to prevent situations when a few visitors will overload our site just by using a map. We will use <a href="https://locust.io/">locust</a> for our tests.</p><p>To get objective results, we need to exclude the case of query caching on the side of the database. To reach this, every request will have its own random viewport (map borders). But now we have some uncertainty about how many points will be clustered. Requesting a processing speed depends on the number of points covered with the query. We want to add this parameter to the statistic to see the dependence of processing time on the number of points.</p><p>Unfortunately, it’s not ordinary to do this in locust. Many things in locust are hardcoded. Here’s a <a href="https://github.com/locustio/locust/issues/1613.">link to an issue about this</a>.</p><p>I found an <a href="https://github.com/locustio/locust/tree/master/examples/extend_web_ui">example of how to extend locust’s Web UI</a>.</p><p>But it just creates a separate address to another tab with a separate table, while the main stats table doesn&#39;t have the needed data.</p><p>I like locust very much and plan to contribute to the project to make such things less complicated. But if I do it now — this article won’t be useful :).</p><p>That’s why we will try to do it our own way. In this article, we will extend WebUI.</p><p>First, we will use locust as a library. Here’s <a href="https://github.com/locustio/locust/blob/master/examples/use_as_lib.py">an example</a>.</p><p>This gives us more possibilities to tune the environment.</p><p>To start, create a locust folder in our project. We’ll place all the needed files here. Next, create a file called load_test.py.</p><p>Here we will create a new WebsiteUser class with tasks to run. We inherit it from the FastHttpUser class as it allows us to set up timeouts.</p><pre>class WebsiteUser(FastHttpUser):<br>    wait_time = between(5, 10)<br>    network_timeout = 10<br>    connection_timeout = 10<br>    host = &quot;http://localhost:8000&quot;<br><br>    def get_filter(self):<br>        min_lat_filter = uniform(min_lat, min_lat + 0.189)<br>        max_lat_filter = uniform(max_lat, max_lat - 0.189)<br>        min_lon_filter = uniform(min_lon, min_lon - 0.19)<br>        max_lon_filter = uniform(max_lon, max_lon + 0.19)<br>        return f&quot;min_lat={min_lat_filter}&amp;max_lat={max_lat_filter}&amp;min_lon={min_lon_filter}&amp;max_lon={max_lon_filter}&quot;<br><br>    # @tag(&quot;fast&quot;, &quot;slow&quot;, &quot;js&quot;)<br>    @task<br>    def list_paginated(self):<br>        self.client.get(&quot;/api/vehicles/&quot;)<br><br>    @tag(&quot;js&quot;)<br>    @task<br>    def js_clustering(self):<br>        filter_str = self.get_filter()<br>        self.client.get(f&quot;/api/vehicles/js_clustering/?{filter_str}&quot;)<br><br>    @tag(&quot;slow&quot;)<br>    @task<br>    def slow_map(self):<br>        filter_str = self.get_filter()<br>        self.client.get(f&quot;/api/vehicles/map/?{filter_str}&quot;)<br><br>    @tag(&quot;fast&quot;)<br>    @task<br>    def fast_map(self):<br>        filter_str = self.get_filter()<br>        self.client.get(<br>            f&quot;/api/vehicles/map_fast/?{filter_str}&quot;,<br>        )</pre><p>Then we will write the code to start our tasks. The user can specify which command line args they want to run to start. Here’s the code:</p><pre>def main(tags):<br>    global env<br>    # setup Environment and Runner<br>    env = UserStatsEnvironment(<br>        user_classes=[WebsiteUser],<br>        events=events,<br>        locustfile=&quot;Clustering Django&quot;,<br>        tags=tags or None,<br>    )<br>    runner = env.create_local_runner()<br><br>    # start a WebUI instance<br>    web_ui = env.create_web_ui(&quot;0.0.0.0&quot;, 8089)<br><br>    # execute init event handlers (only really needed if you have registered any)<br>    env.events.init.fire(environment=env, runner=runner, web_ui=web_ui)<br><br>    # start a greenlet that periodically outputs the current stats<br>    gevent.spawn(stats_printer(env.stats))<br><br>    # start a greenlet that save current stats to history<br>    gevent.spawn(stats_history, env.runner)<br><br>    # start the test<br>    runner.start(1, spawn_rate=10)<br><br>    # in 60 seconds stop the runner<br>    gevent.spawn_later(60, lambda: runner.quit())<br><br>    # wait for the greenlets<br>    runner.greenlet.join()<br><br>    # stop the web server for good measures<br>    web_ui.stop()<br><br><br>def init_parser():<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;tags&quot;, nargs=&quot;*&quot;)<br>    return parser<br><br><br>if __name__ == &quot;__main__&quot;:<br>    parser = init_parser()<br>    args = parser.parse_args()<br>    main(args.tags)</pre><p>Second, we need to collect additional statistical data (point count and cluster count). Then, we need to render this data. Extending or modifying the environment.stats (class RequestStats) needs a lot of work to make it accurate, so we won’t do it.</p><p>Instead, we will create two additional env attributes: one dict is for stats data, and the second one is for table headers on the WebUI page. As you see in the next code block, we create our own environment UserStatsEnvironment.</p><p>Here we add new attributes, user_stats and user_stats_headers, and use our new WebUI subclass, UserStatsWebUI, to render our statistics in the browser.</p><pre>class UserStatsEnvironment(Environment):<br>    user_stats = None<br>    user_stats_headers = None<br><br>    def __init__(<br>        self,<br>        *,<br>        user_classes=None,<br>        shape_class=None,<br>        tags=None,<br>        locustfile: str = None,<br>        exclude_tags=None,<br>        events=None,<br>        host=None,<br>        reset_stats=False,<br>        stop_timeout=None,<br>        catch_exceptions=True,<br>        parsed_options=None,<br>        available_user_classes=None,<br>        available_shape_classes=None,<br>    ):<br>        super().__init__(<br>            user_classes=user_classes,<br>            shape_class=shape_class,<br>            tags=tags,<br>            locustfile=locustfile,<br>            exclude_tags=exclude_tags,<br>            events=events,<br>            host=host,<br>            reset_stats=reset_stats,<br>            stop_timeout=stop_timeout,<br>            catch_exceptions=catch_exceptions,<br>            parsed_options=parsed_options,<br>            available_user_classes=available_user_classes,<br>            available_shape_classes=available_shape_classes,<br>        )<br>        self.user_stats = {}<br>        self.user_stats_headers = {<br>            &quot;vehicles_count&quot;: &quot;Points Count&quot;,<br>            &quot;clusters_count&quot;: &quot;Clusters Count&quot;,<br>        }<br><br>    def create_web_ui(<br>        self,<br>        host=&quot;&quot;,<br>        port=8089,<br>        auth_credentials=None,<br>        tls_cert=None,<br>        tls_key=None,<br>        stats_csv_writer=None,<br>        delayed_start=False,<br>        userclass_picker_is_active=False,<br>    ) -&gt; UserStatsWebUI:<br>        self.web_ui = UserStatsWebUI(<br>            self,<br>            host,<br>            port,<br>            auth_credentials=auth_credentials,<br>            tls_cert=tls_cert,<br>            tls_key=tls_key,<br>            stats_csv_writer=stats_csv_writer,<br>            delayed_start=delayed_start,<br>            userclass_picker_is_active=userclass_picker_is_active,<br>        )<br>        return self.web_ui</pre><p>We will fill our user_stats in the event handler. It will be a dictionary with the same keys as the main locust’s stats dictionary. On every request, we will add needed data to this list.</p><pre>@events.request.add_listener<br>def stats_request_handler(<br>    request_type,<br>    name,<br>    response_time,<br>    response_length,<br>    response,<br>    context,<br>    exception,<br>    start_time,<br>    url,<br>    **kwargs,<br>):<br>    if exception:<br>        env.user_stats[(name, request_type)] = {<br>            &quot;vehicles_count&quot;: 0,<br>            &quot;clusters_count&quot;: 0,<br>        }<br>    else:<br>        if &quot;map&quot; in name:<br>            vehicles_count = sum(i[&quot;vehicles_count&quot;] for i in response.json())<br>            clusters_count = len(response.json())<br>        else:<br>            vehicles_count = len(response.json())<br>            clusters_count = 0<br>        env.user_stats[(name, request_type)] = {<br>            &quot;vehicles_count&quot;: vehicles_count,<br>            &quot;clusters_count&quot;: clusters_count,<br>        }</pre><p>Now, let’s consider WebUI rendering. We can’t easily extend the main template that adds our user stats — statistic rendering is out of the jinja’s template; it’s handled with the jqote library. We have to create a new template. Also, we can’t specify its location without modifying the locust classes. That’s why we need to subclass WebUI and replace it in the environment. In the new WebUI subclass, we need to rewrite the __init__ method, where all the built-in WebUI pages are defined. Look at the code (here, it’s cut to be more readable. You can find more code in the <a href="https://github.com/chkur/clustering_example_for_article">repo</a>).</p><pre>class UserStatsWebUI(WebUI):<br>    def __init__(<br>        self,<br>        environment: &quot;UserStatsEnvironment&quot;,  # CHANGED!<br>        host: str,<br>        port: int,<br>        auth_credentials: Optional[str] = None,<br>        tls_cert: Optional[str] = None,<br>        tls_key: Optional[str] = None,<br>        stats_csv_writer: Optional[StatsCSV] = None,<br>        delayed_start=False,<br>        userclass_picker_is_active=False,<br>    ):<br><br>        # THERE ARE MANY, MANY LINES OF CODE FROM locust SOURCES...<br>        # EVEN MORE...<br>        # Look for them in the repo<br><br>        @app.route(&quot;/&quot;)<br>        @self.auth_required_if_enabled<br>        def index() -&gt; str | Response:<br>            if not environment.runner:<br>                return make_response(<br>                    &quot;Error: Locust Environment does not have any runner&quot;, 500<br>                )<br>            self.update_template_args()<br>            # Here we could replace template, if it wasn&#39;t hardcoded<br>            return render_template(LOCUST_INDEX_HTML, **self.template_args)<br><br>        # THERE ARE MORE LINES OF CODE FROM locust SOURCES...<br>        # EVEN MORE...<br>        # Look for them in the repo<br><br>            for s in chain(<br>                sort_stats(environment.runner.stats.entries),<br>                [environment.runner.stats.total],<br>            ):<br>                stats.append(<br>                    {<br>                        &quot;method&quot;: s.method,<br>                        &quot;name&quot;: s.name,<br>                        &quot;safe_name&quot;: escape(s.name, quote=False),<br>                        &quot;num_requests&quot;: s.num_requests,<br>                        &quot;num_failures&quot;: s.num_failures,<br>                        &quot;avg_response_time&quot;: s.avg_response_time,<br>                        &quot;min_response_time&quot;: 0<br>                        if s.min_response_time is None<br>                        else proper_round(s.min_response_time),<br>                        &quot;max_response_time&quot;: proper_round(s.max_response_time),<br>                        &quot;current_rps&quot;: s.current_rps,<br>                        &quot;current_fail_per_sec&quot;: s.current_fail_per_sec,<br>                        &quot;median_response_time&quot;: s.median_response_time,<br>                        &quot;ninetieth_response_time&quot;: s.get_response_time_percentile(0.9),<br>                        &quot;ninety_ninth_response_time&quot;: s.get_response_time_percentile(<br>                            0.99<br>                        ),<br>                        &quot;avg_content_length&quot;: s.avg_content_length,<br>                        # ADDED: Pass data to response<br>                        **environment.user_stats.get((s.name, s.method), {}),<br>                    }<br>                )<br><br>        # THERE ARE MORE LINES OF CODE FROM locust SOURCES...<br>        # EVEN MORE...<br>        # Look for them in the repo<br><br>            report = {<br>                &quot;stats&quot;: truncated_stats,<br>                &quot;errors&quot;: errors[:500],<br>                &quot;user_stats_headers&quot;: list(<br>                    environment.user_stats_headers.keys()<br>                ),  # Keep order<br>            }<br><br>        # AND MORE LINES OF CODE FROM locust SOURCES...<br>        # EVEN MORE...<br>        # Look for them in the repo<br><br>    def update_template_args(self):<br>        super().update_template_args()<br>        self.template_args[&quot;user_stats_headers&quot;] = self.environment.user_stats_headers<br>        # Here locust uses https://github.com/efeminella/jqote2-template-loader,<br>        # we need pass formatted string<br>        self.template_args[&quot;js_user_stats_rows&quot;] = &quot;\n&quot;.join(<br>            [<br>                f&quot;&lt;td&gt;&lt;%= this.{name} || &#39;-&#39; %&gt;&lt;/td&gt;&quot;<br>                for name in self.environment.user_stats_headers<br>            ]<br>        )</pre><p>Here are the changes for the index.html. We have to pass headers and place for data rows to the template:</p><pre>{% for stat_header in user_stats_headers.values() %}<br>&lt;th class=&quot;stats_label&quot; href=&quot;#&quot; title=&quot;{stat_header}&quot;&gt;{{ stat_header }}&lt;/th&gt;<br>{% endfor %}<br>...<br>{{ js_user_stats_rows }}</pre><p>Before testing, we have to start our project. Testing on Django’s devserver is not the best thing we can do. So we will add gunicorn to the project’s requirements and change docker-compose to start the project with the gunicorn:</p><pre>bash -c &quot;python /home/app/web/manage.py migrate &amp;&amp; python /home/app/web/manage.py collectstatic --no-input || true &amp;&amp; gunicorn clustering_example.wsgi:application --bind 0.0.0.0:8000 --workers 3 --timeout 300&quot;</pre><p>As we specified in port 8000, we can work with gunicorn now, as we worked with the Django devserver before.</p><p>Also, we need to process static files with Django. It’s a bad choice, but for our test project, it is acceptable. The first reason is that we need static files for the admin panel, and the second, our project is just for testing, so we need less code. We will set up STATIC_ROOT in settings.py and add staticfiles_urlpatterns to the urlpatterns list. Now, let’s run the project with the following command:</p><pre>docker-compose up</pre><p>We will run tests for options with clustering in js:</p><pre>docker-compose exec web python locust/load_test.py js</pre><p>But, since we set the timeout value to ten seconds, we get 100% timeouts. With statement_timeout = 10s in PostgreSQL, those queries will be killed in PostgreSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c1sIGMVc4bZiGOVB" /></figure><p>Here’s how to handle 100% timeouts with clustering without snapping to the grid:</p><pre>docker-compose exec web python locust/load_test.py slow</pre><p>In this case, statement_timeout=10s in PostgreSQL does not kill the queries. They stay in the background (as I wrote in a previous article, I suppose it’s a bug in PostGIS, but I failed to register to create an issue. Shame on me).</p><p>Keep in mind, you have to restart docker to clear all running queries after testing with the slow tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jQp6JdEcFREredEt" /></figure><p>At last, we will run clustering on the PostgreSQL side while snapping to the grid.</p><pre>docker-compose exec web python locust/load_test.py fast</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DiA7v0p27m_fKZD8" /></figure><p>As you see, we can evaluate how the points affect the query execution time. The average time I get is about three seconds per request. It’s not too fast but is acceptable for such requests on a site that’s not hard-loaded.</p><p>It will be reasonable to set up <a href="https://www.django-rest-framework.org/api-guide/throttling/">throttling</a>. If your site grows (I hope it will), you can set up replication for your database and move such long queries to the replica. Also, it will be useful to set up your web server to separate settings for these queries (timeouts, etc.).</p><p>If it’s not enough, think about moving this code to the serverless functions.</p><p>After database growth, you may experience performance issues. In some cases, table partitioning may help speed up your database queries. The next article will set up table partitioning in the existing Django project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79111a1de334" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/customize-testing-with-locust-79111a1de334">Customize Testing With Locust</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Geo Clustering in a Django Project]]></title>
            <link>https://medium.com/better-programming/geoclustering-in-django-project-ba0c0511e3dd?source=rss-998425d33551------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba0c0511e3dd</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[postgis]]></category>
            <dc:creator><![CDATA[Sergey Bachurin]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 11:27:46 GMT</pubDate>
            <atom:updated>2023-02-07T21:23:35.458Z</atom:updated>
            <content:encoded><![CDATA[<h4>Geoclustering with Django and PostGIS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*bVRpXAzAQoNPh8N2PSojOw.jpeg" /><figcaption>This is a preview I generated with DeepAI. It shows the query “map and clusters”</figcaption></figure><p>In this article, we’ll use an existing Django Rest Framework project with a PostGIS database and frontend on VueJS. There are about ~100,000 items in the testing database and five kinds of items. These items have common fields, such as title, description, price, location, and some specific fields for each of these five types.</p><p>There are about 20–30 fields for characteristics for every item, and we have common and specific filters for most fields. These filters were realized mostly with <a href="https://github.com/carltongibson/django-filter/">Django-filter</a>, and work fine enough.</p><p>First, we create a new task for this project — to show these items on the map while applying any available filtering. We need to merge nearby markers to display them as one big marker with the items’ counts. If there is just one item, we will show the item details.</p><p>Two of the main problems are:</p><ul><li>We need working ORM queries to display the items’ lists.</li><li>It is highly desirable to not duplicate or separate data-selecting logic to display lists and maps.</li></ul><p>I’ll create a small test project to illustrate this problem’s solution.</p><p>After getting started, we may try the following options:</p><ul><li>Transfer all data to the frontend side and use a js library like Google Maps’s <a href="https://github.com/googlemaps/js-markerclusterer">markerclusterer</a>. In this case, we already have all the needed queries; we just need to remove pagination to get all the data. To do that, we should select all the needed data from the database, then parse it to transfer it to the frontend. On the client side, we make clusters. This will take too much time and resources, so in many cases, we will have senseless overload using this option.</li><li>Make clusters on the backend side in Python. We can use libs like sklearn for this. In this case, we also don’t need to change our ORM queries, just remove pagination. But here, we need to load a large amount of data from the database, move it to Python, and parse it there. It will not be fast.</li><li>Make clusters on the database side. Here we eliminate unnecessary data transfers and process our data the fastest way. But here, we should resolve the problem of not duplicating our queries for data filtering.</li></ul><p>Let’s discuss clustering by creating a test project.</p><ul><li>You can get the code at <a href="https://github.com/chkur/clustering_example_for_article.git">https://github.com/chkur/clustering_example_for_article</a>.</li><li>You should have docker and docker-compose installed to run it.</li></ul><p>Clone the repository and start a project in docker. Here’s how to do that:</p><pre>git clone https://github.com/chkur/clustering_example_for_article.git<br>docker-compose up –build</pre><p>For our example, let’s take a dataset with spatial data. Management commands will download the sample files and import them to the database. Here’s the command:</p><pre>docker-compose up exec web python manage.py import_rows</pre><p>Our sample file is located at <a href="https://data.cityofchicago.org/Service-Requests/311-Service-Requests-Abandoned-Vehicles-Historical/3c9v-pnva">https://data.cityofchicago.org/Service-Requests/311-Service-Requests-Abandoned-Vehicles-Historical/3c9v-pnva</a>. It has about 260 thousand records with geodata. You can download it manually, place it in the project subfolder, files, and run the same command to import data.</p><p>Swagger (<a href="http://localhost:8000/api/doc/swagger/">http://localhost:8000/api/doc/swagger/</a>) will help you run a query with the needed parameters. To check the loading requests manually, we will use <a href="https://github.com/jazzband/django-silk">silk</a>. And for load testing, we will use <a href="https://locust.io/">locust</a>.</p><h3>Get Data for Paginated Text Representation</h3><p>Our single project model is simple and repeats the CSV file fields. It does not have any relations, which simplifies our queries. Our first view will be simple — it just shows a paginated list. There are no problems. It has simple queries and small responses because of pagination.</p><pre>class VehicleSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Vehicle<br>        exclude = [&quot;id&quot;]<br><br>class VehicleListView(ListAPIView):<br>    &quot;&quot;&quot;Paginated list view for showing all.&quot;&quot;&quot;<br><br>    serializer_class = VehicleSerializer<br>    filter_backends = [filters.DjangoFilterBackend]<br>    filterset_class = VehicleFilter<br>    queryset = Vehicle.objects.all()</pre><p>You can test this query running GET <a href="http://localhost:8000/api/vehicles/">http://localhost:8000/api/vehicles/</a>.</p><h3>Get Data for JS Clustering</h3><p>Now, we’ll try clustering on the client side because minimal backend code changes are needed. We need to remove extra fields, which we will not show on the map in the serializer, and remove pagination to transfer all data to the frontend side.</p><pre>class VehicleForJSSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Vehicle<br>        fields = [<br>            &quot;vehicle_make&quot;,<br>            &quot;vehicle_make&quot;,<br>            &quot;vehicle_color&quot;,<br>            &quot;creation_date&quot;,<br>            &quot;completion_date&quot;,<br>            &quot;type_of_service_request&quot;,<br>            &quot;location&quot;,<br>        ]</pre><p>We detect map borders with the get_queryset method, so we can restrict our query with map borders. We can create a new filter for the queryset with polygon, but we will leave all the code for map clustering in views.</p><p>Create a new base view to define the get_queryset method.</p><pre>class BaseMapListView(ListAPIView):<br>    queryset = Vehicle.objects.all()<br>    filter_backends = [filters.DjangoFilterBackend]<br>    filterset_class = VehicleFilter<br><br>    # Map options for filtering and clustering<br>    polygon = None<br>    max_distance_between_objects = None<br>    grid_cell_size = None<br><br>    def set_map_options(self, request):<br>        # Here we assume that all points will be in one western hemisphere<br>        # In real project here we should also check 180 degrees<br>        # to avoid problems when borders are in different hemispheres<br>        max_lat = float(request.query_params.get(&quot;max_lat&quot;, 180))<br>        min_lat = float(request.query_params.get(&quot;min_lat&quot;, -180))<br>        max_lon = float(request.query_params.get(&quot;max_lon&quot;, 90))<br>        min_lon = float(request.query_params.get(&quot;min_lon&quot;, -90))<br>        self.polygon = Polygon(<br>            [<br>                (min_lon, min_lat),<br>                (min_lon, max_lat),<br>                (max_lon, max_lat),<br>                (max_lon, min_lat),<br>                (min_lon, min_lat),<br>            ],<br>            srid=4326,<br>        )<br>        self.max_distance_between_objects = (<br>            Point(max_lon, max_lat).distance(Point(min_lon, min_lat))<br>            / settings.MAP_MAX_OBJECTS_IN_LINE<br>        )<br>        self.grid_cell_size = (<br>            Point(max_lon, max_lat).distance(Point(min_lon, min_lat))<br>            / settings.MAP_GRID_CELL_COUNT<br>        )<br><br>    def get_queryset(self):<br>        self.set_map_options(self.request)<br>        queryset = super().get_queryset()<br>        queryset = self.filter_queryset(queryset)<br>        queryset = queryset.filter(<br>            location__isnull=False,<br>            location__coveredby=self.polygon,<br>        )<br>        return queryset</pre><p>Here we will apply all the needed filtering for our map views and create our new view with the base class BaseMapListView.</p><pre>class VehicleNotPaginatedListView(BaseMapListView):<br>    &quot;&quot;&quot;Not paginated list view for js clustering&quot;&quot;&quot;<br><br>    serializer_class = VehicleForJSSerializer<br>    pagination_class = None<br><br>    @silk_profile(name=&quot;Not paginated list&quot;)<br>    def list(self, request, *args, **kwargs):<br>        queryset = self.get_queryset()<br>        serializer = self.get_serializer(queryset, many=True)<br>        return Response(serializer.data)</pre><p>Now, we will run GET-query at <a href="http://localhost:8000/api/vehicles/">http://localhost:8000</a><a href="http://localhost:8000/api/doc/swagger/#/vehicles/vehicles_js_clustering_list">/api/vehicles/js_clustering/</a>.</p><p>At first, we will see hard CPU loading with the Django process, but it’s not hard for PostgreSQL — just select some fields of all rows in the database. But then our Django project has to receive all this data, wrap it with the serializer to the response, and give it to the frontend. That’s hard work for Python.</p><p>After waiting 48 seconds (on my laptop, which has the Ryzen 5 4500 processor and 16 Gb of RAM), I got a response with ~260 thousand records. After that, our browser will need to parse all this data. It’s not an acceptable result for our purposes.</p><h3>Requests Results</h3><p><a href="http://localhost:8000/api/vehicles/js_clustering/?max_lat=41.9&amp;max_lon=-87.7&amp;min_lat=41.85&amp;min_lon=-87.77">http://localhost:8000/api/vehicles/js_clustering/?max_lat=41.9&amp;max_lon=-87.7&amp;min_lat=41.85&amp;min_lon=-87.77</a> (~14,000 records for clustering)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/0*mX9g2wYQDor7X7VY" /></figure><p><a href="http://localhost:8000/api/vehicles/js_clustering/?max_lat=41.9&amp;max_lon=-87.6&amp;min_lat=41.85&amp;min_lon=-87.77">http://localhost:8000/api/vehicles/js_clustering/?max_lat=41.9&amp;max_lon=-87.6&amp;min_lat=41.85&amp;min_lon=-87.77</a> (~30,000 records for clustering)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/0*kQ_l6njfUTUJVYcj" /></figure><p><a href="http://localhost:8000/api/vehicles/js_clustering/?max_lat=42&amp;max_lon=-87.6&amp;min_lat=41.8491660012213&amp;min_lon=-87.70814559957574">http://localhost:8000/api/vehicles/js_clustering/?max_lat=42&amp;max_lon=-87.6&amp;min_lat=41.8491660012213&amp;min_lon=-87.70814559957574</a> (~57,000 records for clustering)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/0*cBoB_st-VkwLpPKm" /></figure><h3>Get Clustered Data From the Database</h3><p>Now, we will make all clustering work on the PostgreSQL side. There are no implemented functions like ST_ClusterKMeans or ST_ClusterDBScan in Django, so we will use SQL to apply them. First, we need to save all our filters. After getting the queryset from BaseMapListView.get_queryset(), we will save its text for use as a subquery. We’ll make it in the new method clusterize:</p><pre>def clusterize(self, queryset):<br>        query = queryset.values(<br>            &quot;location&quot;,<br>            &quot;vehicle_color&quot;,<br>            &quot;vehicle_make&quot;,<br>            &quot;creation_date&quot;,<br>            &quot;completion_date&quot;,<br>            &quot;type_of_service_request&quot;,<br>        ).query<br>        sql, params = query.sql_with_params()<br><br>        map_query = self.get_map_query().format(<br>            sql=sql,<br>            self=self,<br>        )<br>        with connection.cursor() as cursor:<br>            cursor.execute(map_query, params)<br>            columns = [col[0] for col in cursor.description]<br>            data = []<br>            for row in cursor.fetchall():<br>                data_item = dict(zip(columns, row))<br>                data_item[&quot;location&quot;] = Point(<br>                    data_item.pop(&quot;lon&quot;),<br>                    data_item.pop(&quot;lat&quot;),<br>                )<br>                data.append(data_item)<br>        return data<br><br>   def list(self, request, *args, **kwargs):<br>        queryset = self.get_queryset()<br>        result_data = self.clusterize(queryset)<br>        serializer = self.serializer_class(result_data, many=True)<br>        return Response(serializer.data)</pre><p>Here we store the SQL expression for our queryset in two variables and call the new method get_map_query to get the result query for the map. Let’s look at this query closely:</p><pre>def get_map_query(self):<br>        return &quot;&quot;&quot;<br>            -- Assign clusters for every record in the queryset according to its location and calculated distance<br>            WITH clustered_locations AS<br>            (SELECT ST_ClusterDBScan(location, {self.max_distance_between_objects}, 1) over() AS cluster,<br>                    vehicle_color,<br>                    vehicle_make,<br>                    creation_date,<br>                    completion_date,<br>                    type_of_service_request,<br>                    location<br>            FROM ({sql}) q1 ),<br>            -- Subquery count items count for every cluster in first subquery and calculate its center<br>                t1 AS<br>            (SELECT cluster,<br>                    avg(ST_X(location)) as lon,<br>                    avg(ST_Y(location)) as lat,<br>                    count(*) AS vehicles_count<br>            FROM clustered_locations<br>            GROUP BY cluster),<br>            -- Subquery selects 1st row for every cluster to add this data for rows with count=1<br>                t2 AS<br>            (SELECT DISTINCT ON (cluster) vehicle_color,<br>                                vehicle_make,<br>                                creation_date,<br>                                completion_date,<br>                                type_of_service_request,<br>                                location,<br>                                cluster<br>            FROM clustered_locations)<br>            -- Main query merge cluster data (location + items count) with additional information for clusters with one item only<br>            SELECT t1.*,<br>                CASE<br>                    WHEN t1.vehicles_count = 1 THEN t2.vehicle_make<br>                    ELSE NULL<br>                END AS vehicle_make,<br>                CASE<br>                    WHEN t1.vehicles_count = 1 THEN t2.vehicle_color<br>                    ELSE NULL<br>                END AS vehicle_color,<br>                CASE<br>                    WHEN t1.vehicles_count = 1 THEN t2.creation_date<br>                    ELSE NULL<br>                END AS creation_date,<br>                CASE<br>                    WHEN t1.vehicles_count = 1 THEN t2.completion_date<br>                    ELSE NULL<br>                END AS completion_date,<br>                CASE<br>                    WHEN t1.vehicles_count = 1 THEN t2.type_of_service_request<br>                    ELSE NULL<br>                END AS type_of_service_request<br>            FROM t1<br>            INNER JOIN t2 ON t1.cluster=t2.cluster<br>        &quot;&quot;&quot;</pre><p>As you can see, we use three new subqueries and one main query here. We create clusters with the PostGIS function ST_ClusterDBScan, then use aggregation functions avg and count to get a list of clusters with their locations and item counts in each.</p><p>In the third subquery, we select one row with additional data for every cluster. In the main query, we merge the clusters list with additional data if there is only one item in the row. For all other clusters, there will be null.</p><p>This query works fine when selecting a few thousand records, but it becomes slow on larger selections. Clustering, as a window function, calculates after the subquery is computed and repeats iteratively until needed conditions on distance are met. So, if we want to speed up this process — we need to reduce the number of iterations.</p><h3>Requests Results</h3><p><a href="http://localhost:8000/api/vehicles/map/?max_lat=41.9&amp;max_lon=-87.7&amp;min_lat=41.85&amp;min_lon=-87.77">http://localhost:8000/api/vehicles/map/?max_lat=41.9&amp;max_lon=-87.7&amp;min_lat=41.85&amp;min_lon=-87.77</a> (~14,000 records for clustering)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/0*QsAdHbWdqUooPBNf" /></figure><p><a href="http://localhost:8000/api/vehicles/map/?max_lat=41.9&amp;max_lon=-87.6&amp;min_lat=41.85&amp;min_lon=-87.77">http://localhost:8000/api/vehicles/map/?max_lat=41.9&amp;max_lon=-87.6&amp;min_lat=41.85&amp;min_lon=-87.77</a> (~30,000 records for clustering)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/0*U6YJuXYvwHcnD_Hs" /></figure><p><a href="http://localhost:8000/api/vehicles/map/?max_lat=42&amp;max_lon=-87.6&amp;min_lat=41.8491660012213&amp;min_lon=-87.70814559957574">http://localhost:8000/api/vehicles/map/?max_lat=42&amp;max_lon=-87.6&amp;min_lat=41.8491660012213&amp;min_lon=-87.70814559957574</a> (~57,000 records for clustering)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/0*LXAR_4VIeQW171za" /></figure><p>Here we get an unpleasant thing: it looks like there is a bug in the implementation of ST_ClusterDBScan; it does not interrupt on statement_timeout in PostgreSQL. Unfortunately, PostGIS has an unfriendly tracking system. I didn’t have the time to deal with the complicated registration process, so I couldn’t create a ticket.</p><h3>Get Clustered Data From the Database With Snapped-to-Grid Locations</h3><p>We aim to reduce the number of iterations. For that, we will snap the initial locations of our points to the grid, so many neighbor points will merge into one on this step. It’s important to save the balance between speed and accuracy, so you have to determine the optimal grid size empirically.</p><p>Now, we will turn the last view into a subclass with SQL-based clustering. We will need to rewrite the get_map_query method, which returns the result SQL query.</p><pre>def get_map_query(self):<br>        return &quot;&quot;&quot;<br>            -- Snap to grid every location in the database<br>            WITH rounded_locations AS<br>            (SELECT ST_SnapToGrid(location, {self.grid_cell_size}) AS grid_location,<br>                    vehicle_color,<br>                    vehicle_make,<br>                    creation_date,<br>                    completion_date,<br>                    type_of_service_request,<br>                    location<br>            FROM ({sql}) q1 ),<br>            -- Calculate clusters for every grid location in new subquery<br>                clusters_tmp AS<br>            (SELECT grid_location,<br>                    ST_ClusterDBScan(grid_location, {self.max_distance_between_objects}, 1) over() AS cluster<br>            FROM<br>                (SELECT DISTINCT grid_location<br>                FROM rounded_locations) grid_points ),<br>            -- Add clusters to snapped to grid items<br>                clustered_locations AS<br>            (SELECT rounded_locations.*,<br>                    clusters_tmp.cluster<br>            FROM rounded_locations<br>            INNER JOIN clusters_tmp ON clusters_tmp.grid_location = rounded_locations.grid_location),<br>                t1 AS<br>            (SELECT cluster,<br>                    avg(ST_X(location)) as lon,<br>                    avg(ST_Y(location)) as lat,<br>                    count(*) AS vehicles_count<br>            FROM clustered_locations<br>            GROUP BY cluster),<br>                t2 AS<br>            (SELECT DISTINCT ON (cluster) vehicle_color,<br>                                vehicle_make,<br>                                creation_date,<br>                                completion_date,<br>                                type_of_service_request,<br>                                location,<br>                                cluster<br>            FROM clustered_locations)<br>            -- Main query merges cluster data (location + items count) with additional information for clusters with one item only<br>            SELECT t1.*,<br>                CASE<br>                    WHEN t1.vehicles_count = 1 THEN t2.vehicle_make<br>                    ELSE NULL<br>                END AS vehicle_make,<br>                CASE<br>                    WHEN t1.vehicles_count = 1 THEN t2.vehicle_color<br>                    ELSE NULL<br>                END AS vehicle_color,<br>                CASE<br>                    WHEN t1.vehicles_count = 1 THEN t2.creation_date<br>                    ELSE NULL<br>                END AS creation_date,<br>                CASE<br>                    WHEN t1.vehicles_count = 1 THEN t2.completion_date<br>                    ELSE NULL<br>                END AS completion_date,<br>                CASE<br>                    WHEN t1.vehicles_count = 1 THEN t2.type_of_service_request<br>                    ELSE NULL<br>                END AS type_of_service_request<br>            FROM t1<br>            INNER JOIN t2 ON t1.cluster=t2.cluster<br>            &quot;&quot;&quot;</pre><ul><li>In the first subquery, rounded_locations, we snap points to the grid, creating a field, grid_location.</li><li>In the second subquery, clusters_tmp, we calculate clusters for every new location.</li><li>In the subquery, clustered_locations, we merge clusters with the subquery, rounded_locations.</li><li>In subquery, t1, we calculate the average position and item count for every cluster.</li><li>In subquery, t2, we select additional data for clusters (this data will only be applied to single rows).</li></ul><p>At last, we merge subqueries t1 and t2 into the result query.</p><h3>Requests Results</h3><p><a href="http://localhost:8000/api/vehicles/map_fast/?max_lat=41.9&amp;max_lon=-87.7&amp;min_lat=41.85&amp;min_lon=-87.77">http://localhost:8000/api/vehicles/map_fast/?max_lat=41.9&amp;max_lon=-87.7&amp;min_lat=41.85&amp;min_lon=-87.77</a> (~14,000 records for clustering)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/0*zaEv6uOFPgKrQtaI" /></figure><p><a href="http://localhost:8000/api/vehicles/map_fast/?max_lat=41.9&amp;max_lon=-87.6&amp;min_lat=41.85&amp;min_lon=-87.77">http://localhost:8000/api/vehicles/map_fast/?max_lat=41.9&amp;max_lon=-87.6&amp;min_lat=41.85&amp;min_lon=-87.77</a> (~30,000 records for clustering)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/0*TqMGS0Uzt-tvhAm0" /></figure><p><a href="http://localhost:8000/api/vehicles/map_fast/?max_lat=42&amp;max_lon=-87.6&amp;min_lat=41.8491660012213&amp;min_lon=-87.70814559957574">http://localhost:8000/api/vehicles/map_fast/?max_lat=42&amp;max_lon=-87.6&amp;min_lat=41.8491660012213&amp;min_lon=-87.70814559957574</a> (~57,000 records for clustering)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/0*52kwAEq9UQRrBEcM" /></figure><p>So, we can get an acceptable result by combining grid-snapping and clustering via PostgreSQL. You will get better results with PostgreSQL tuning.</p><h3>Testing</h3><p>Write some tests to check that all map endpoints get approximately the same data in response and use all needed filters. We will create records for our tests that we can easily filter.</p><p>In our GeoTestCase, we create three tests. In the first one, we don’t use filters, and in the other two, we use filters. In rare cases, there may be small differences between cluster counts due to the clustering algorithm and approximation in the last clustering method. That’s why we use assertAlmostEqual to compare the cluster count.</p><pre>from datetime import date<br>from random import uniform<br><br>from django.contrib.gis.geos import Point<br><br>from rest_framework.test import APITestCase<br><br>from ddf import G<br><br>from .models import Vehicle<br><br>class GeoTestCase(APITestCase):<br>    def setUp(self) -&gt; None:<br>        def new_vehicles(<br>            min_lon,<br>            min_lat,<br>            vehicle_make=&quot;audi&quot;,<br>            dt=None,<br>            count=10,<br>        ):<br>            for i in range(count):<br>                G(<br>                    Vehicle,<br>                    location=Point(<br>                        uniform(min_lon, min_lon + 0.1),<br>                        uniform(min_lat, min_lat + 0.1),<br>                    ),<br>                    vehicle_make=vehicle_make,<br>                    completion_date=dt,<br>                )<br><br>        new_vehicles(39, 39, dt=date(2020, 1, 1))<br>        new_vehicles(40, 40, dt=date(2020, 1, 1))<br>        new_vehicles(40, 40, dt=date(2022, 1, 1))<br>        new_vehicles(40, 40, &quot;bmw&quot;, dt=date(2022, 1, 1))<br>        new_vehicles(41, 41, dt=date(2020, 1, 1))<br><br>    def test_map_all(self):<br>        &quot;&quot;&quot;Test all map without filtering.<br><br>        Here will be just 1 cluster with all vehicles&quot;&quot;&quot;<br><br>        result = self.client.get(&quot;/api/vehicles/&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        self.assertEqual(result.json()[&quot;count&quot;], 50)<br><br>        result = self.client.get(&quot;/api/vehicles/js_clustering/&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        self.assertEqual(len(result.json()), 50)<br><br>        result = self.client.get(&quot;/api/vehicles/map/&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        self.assertEqual(len(result.json()), 1)<br>        self.assertEqual(result.json()[0][&quot;vehicles_count&quot;], 50)<br><br>        result = self.client.get(&quot;/api/vehicles/map_fast/&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        self.assertEqual(len(result.json()), 1)<br>        self.assertEqual(result.json()[0][&quot;vehicles_count&quot;], 50)<br><br>    def test_map_filter1(self):<br>        &quot;&quot;&quot;Test map with filtering #1<br><br>        As we take random values for map - it&#39;s not known how many clusters will be created<br>        But in common case clusters count in slow endpoint must match clusters count in faster endpoint&quot;&quot;&quot;<br><br>        filter_condition = &quot;?vehicle_make__icontains=audi&amp;min_lat=40&amp;max_lat=40.1&amp;min_lon=40&amp;max_lon=40.1&quot;<br>        result = self.client.get(f&quot;/api/vehicles/{filter_condition}&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        # This endpoint doesn&#39;t use map filtering<br>        self.assertEqual(result.json()[&quot;count&quot;], 40)<br><br>        result = self.client.get(f&quot;/api/vehicles/js_clustering/{filter_condition}&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        self.assertEqual(len(result.json()), 20)<br><br>        result = self.client.get(f&quot;/api/vehicles/map/{filter_condition}&quot;)<br>        self.assertEqual(result.status_code, 200)<br><br>        self.assertEqual(sum(i[&quot;vehicles_count&quot;] for i in result.json()), 20)<br><br>        clusters_count1 = len(result.json())<br><br>        result = self.client.get(f&quot;/api/vehicles/map_fast/{filter_condition}&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        self.assertEqual(sum(i[&quot;vehicles_count&quot;] for i in result.json()), 20)<br><br>        clusters_count2 = len(result.json())<br><br>        self.assertAlmostEqual(clusters_count1, clusters_count2, delta=1)<br><br>    def test_map_filter2(self):<br>        &quot;&quot;&quot;Test map with filtering #2&quot;&quot;&quot;<br><br>        filter_condition = &quot;?vehicle_make__icontains=audi&amp;min_lat=40&amp;max_lat=40.1&amp;min_lon=40&amp;max_lon=40.1&amp;completion_date__lt=2021-01-01&quot;<br>        result = self.client.get(f&quot;/api/vehicles/{filter_condition}&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        # This endpoint doesn&#39;t use map filtering<br>        self.assertEqual(result.json()[&quot;count&quot;], 30)<br><br>        result = self.client.get(f&quot;/api/vehicles/js_clustering/{filter_condition}&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        self.assertEqual(len(result.json()), 10)<br><br>        result = self.client.get(f&quot;/api/vehicles/map/{filter_condition}&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        self.assertEqual(sum(i[&quot;vehicles_count&quot;] for i in result.json()), 10)<br><br>        clusters_count1 = len(result.json())<br><br>        result = self.client.get(f&quot;/api/vehicles/map_fast/{filter_condition}&quot;)<br>        self.assertEqual(result.status_code, 200)<br>        self.assertEqual(sum(i[&quot;vehicles_count&quot;] for i in result.json()), 10)<br><br>       clusters_count2 = len(result.json())<br><br>        self.assertAlmostEqual(clusters_count1, clusters_count2, delta=1)</pre><p>The next article will create load tests for this project with locust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba0c0511e3dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/geoclustering-in-django-project-ba0c0511e3dd">Geo Clustering in a Django Project</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>