<?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 Roman Sorin on Medium]]></title>
        <description><![CDATA[Stories by Roman Sorin on Medium]]></description>
        <link>https://medium.com/@romansorin?source=rss-31f2eb794f49------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2WLXvt9HGh6ASZtNUordJQ.jpeg</url>
            <title>Stories by Roman Sorin on Medium</title>
            <link>https://medium.com/@romansorin?source=rss-31f2eb794f49------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:53:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@romansorin/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[Serializing OpenAI API Responses for Logging with Pydantic]]></title>
            <link>https://medium.com/@romansorin/serializing-openai-api-responses-for-logging-with-pydantic-5b70336b1440?source=rss-31f2eb794f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b70336b1440</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[pydantic]]></category>
            <dc:creator><![CDATA[Roman Sorin]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 03:12:17 GMT</pubDate>
            <atom:updated>2024-02-03T03:12:17.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O900dlA9cH1b5LnnCVIeQQ.png" /><figcaption>Serializing OpenAI API Responses for Logging with Pydantic — Feb 1, 2024</figcaption></figure><h3>TL;DR</h3><pre>from openai import OpenAI<br>from openai.types import CreateEmbeddingResponse<br><br>client: OpenAI = OpenAI(api_key=&quot;YOUR_OPENAI_KEY&quot;)<br><br>embeddings_response: CreateEmbeddingResponse = (<br>  client.embeddings.create(input=[&quot;Some embeddings to generate&quot;])<br>)<br><br># Using Pydantic&#39;s `model_dump_json` method,<br># we can easily serialize any OpenAI responses<br>serialized_response: str = embeddings_response.model_dump_json()<br><br># Now that our response is serialized,<br># we can log and store it as needed<br>openai_response: OpenAiResponse = OpenAiResponse(<br>  embeddings_response=serialized_response,<br>  ...  # other model fields<br>)</pre><h3>Why you might consider serializing responses</h3><p>When working with external APIs, I lean heavily on logging as much information as I can for requests and responses. Recently, I’ve been working on a side project that relies on OpenAI’s <a href="https://platform.openai.com/docs/guides/embeddings">embeddings</a> and <a href="https://platform.openai.com/docs/guides/text-generation/chat-completions-api">chat completions</a> APIs, as well as Amazon Textract’s <a href="https://aws.amazon.com/textract/">OCR service</a>. For these types of external APIs, logging entire responses can be incredibly useful for many reasons, whether it’s trying to iron out pricing for a product or needing to track if you’re receiving a non-deterministic output (<a href="https://platform.openai.com/docs/guides/text-generation/reproducible-outputs">despite configuring for reproducibility</a>). Over time, the quality of outputs can drift over time, and you’ll inevitably need to iterate on input prompts as your product evolves or parameters change, which is where detailed logging provides the opportunity to look at how cost and quality may be changing — almost like a passive A/B test.</p><p>For most small to medium-sized projects, I’ll typically store these logs as a dedicated table or explicit metadata columns on an existing table using Postgres. You <em>could</em> break a response object and its items into dedicated columns, but APIs tend to change over time (sometimes without warning), and I don’t want to spend time maintaining something that will be infrequently used for debugging, replaying requests, or analysis.</p><p>So, as part of this side project, I was attempting to store the response directly into an SQLAlchemy model like so:</p><pre>from openai import OpenAI<br>from openai.types import CreateEmbeddingResponse<br><br>client: OpenAI = OpenAI(api_key=&quot;YOUR_OPENAI_KEY&quot;)<br><br>embeddings_response: CreateEmbeddingResponse = (<br>  client.embeddings.create(input=[&quot;Some embeddings to generate&quot;])<br>)<br><br># This will throw - we can&#39;t store the object directly!<br>openai_response: OpenAiResponse = OpenAiResponse(<br>  embeddings_response=embeddings_response,  # embeddings_response is a JSONB column<br>)</pre><p>This, of course, would not work. Trying to insert this directly into the model would produce an error like TypeError: Object of type CreateEmbeddingResponse is not JSON serializable. While exploring solutions, <a href="https://gist.github.com/CivilEngineerUK/dbd328b72ebee77c3471670bb91fa6df">I came across a gist</a> that created an explicit serialize_completion function to accomplish this. While the approach is straightforward (and unblocked me temporarily while trying to solve an unrelated task!), it’s more work than necessary and would require more maintenance and a similar manual approach for other response types.</p><h3>When in doubt, just read the source code</h3><p>After creating another serializer for the embeddings response, I was frustrated. What if I miss a key or the API changes silently, meaning I may be losing information or have exceptions creeping up? There are many solutions, but I decided I’d jump into the definition for the CreateEmbeddingResponse type. Luckily, OpenAI represents all of their responses as Pydantic models. <a href="https://docs.pydantic.dev/latest/">Pydantic</a> is an extremely powerful data validation library that lets us solve this serialization issue natively, instead of having to come up with our own solution:</p><pre># Using Pydantic&#39;s `model_dump_json` method,<br># we can easily serialize any OpenAI responses<br>serialized_response: str = embeddings_response.model_dump_json()</pre><p>Reviewing the documentation for pydantic.BaseModel, we can find the <a href="https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_dump_json">model_dump_json() method</a> that allows us to serialize it directly to a JSON-encoded string. A simple and obvious solution, but a source of frustration if you don’t know (or forget) where to look. Another personal reminder of why enforcing strong typing is so useful!</p><p><strong>A closing note:</strong> I’m currently building an ETL product based around documents and document-heavy workflows. If you or your organization might be interested, <a href="https://romansorin.com/contact">please let me know</a>!</p><p><em>This post was originally published at </em><a href="https://romansorin.com/"><em>romansorin.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b70336b1440" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Django’s JSONField? You probably don’t need it. Here’s why]]></title>
            <link>https://medium.com/@romansorin/using-djangos-jsonfield-you-probably-don-t-need-it-here-s-why-93478738b887?source=rss-31f2eb794f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/93478738b887</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Roman Sorin]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 01:05:27 GMT</pubDate>
            <atom:updated>2022-04-06T01:05:27.887Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWft3C6r_33iZDkZTqcyyA.png" /><figcaption>Using Django’s JSONField? You probably don’t need it. Here’s why</figcaption></figure><p>In my current role, we use Django with Django Rest Framework (DRF) to power our platform’s API, and leverage PostgreSQL to store both relational and nonrelational data. As part of the platform, we run asynchronous, on-demand batch jobs that can operate up to half a million rows at once.</p><p>Each of these jobs is represented by a row in a table and contains both top-level, single-responsibility columns as well as “deeper” structures that may contain more arbitrary data. As a working proof-of-concept, we avoided over-optimizing early and didn’t have a clear definition of what these job outputs might look like. We added JSON columns to our job model that would store different forms of data — metadata, debug output, and namely, job report output.</p><p>While we didn’t need to expose metadata or debug output to our API, returning the report data to describe the job results was the main requirement. This data varied little in size and complexity, only maintaining a couple of keys and a few levels of nesting.</p><p>This job model did not have any special qualities. It was defined and represented like any other type of model within our Django app, except for additional JSONB columns to represent arbitrary and unnormalized data.</p><p>Unexpectedly, we experienced major slowdowns both in API response time and internal queries made through an RDBMS. At a point, requesting a single one of these jobs would take <em>upwards of 5 minutes</em>. When JSONB columns were omitted from queries, the query had a subsecond execution time.</p><p>Interestingly, we found that converting all columns that did not need to use any of JSONB’s benefits — such as indexing and advanced querying — significantly improved our application’s performance. While I’m doubtful that this was the true culprit, it did get us to our desired performance in the shortest time possible.</p><p>With that personal anecdote, let’s explore the differences between JSONB and JSON, and how you can use JSON in your Django apps.</p><h3>JSONB vs JSON, and how they’re handled</h3><p>Both the JSON and JSONB data types are used for storing JSON data in PostgreSQL tables. These data types are <em>almost</em> identical, different only in how these values are <a href="https://www.postgresql.org/docs/current/datatype-json.html">stored in the database</a>, and the efficiency with which operations [1] are performed.</p><p>Notably, JSON stores the exact input text, whereas JSONB instead stores a decomposed binary format. As a result, there’s a small amount of write/conversion overhead (converting from text to binary), making storing input on this field slightly slower overall. The binary format of JSONB allows for significantly faster processing and operations, as the field does not have to be reparsed each time.</p><p>In addition to the fields represented in a different format, JSONB allows for indexing of keys in the field, which allows for efficient arbitrary key lookups. This would take significantly longer if attempting to search within a JSON field, as you would have to both parse the field and perform a search within a text object.</p><p><strong>In summary,</strong></p><p><strong>JSON:</strong></p><ul><li>Stores an exact copy of the input text, including “semantically-insignificant” whitespace, duplicate keys, and ordering.</li><li>The last value of a duplicate key is used.</li><li>Must reparse the field for each operation, causing these operations to take significantly longer</li></ul><p><strong>JSONB:</strong></p><ul><li>Stores a decomposed binary format, which does not preserve whitespace (outside of values), the order of keys, or duplicate keys. Only the last value of duplicate keys is kept.</li><li>No reparsing is needed and operations over the field are significantly quicker</li><li>Can take up <a href="https://heap.io/blog/when-to-avoid-jsonb-in-a-postgresql-schema">more disk space</a> than a regular JSON column</li><li>Supports indexing of keys, significantly improving the performance of lookups</li></ul><h3>When to use which</h3><p>Deciding which format of JSON to use will largely depend on the needs of your application. Generally, the <a href="https://www.postgresql.org/docs/current/datatype-json.html">Postgres manual suggests</a> that most applications should use the JSONB field, except in specialized circumstances or legacy applications where keys would not be able to be re-ordered on retrieval.</p><p>In normal usage, this makes sense as you are likely to be storing some form of structured yet arbitrary data that you may need to perform operations or lookups on. However, we found that a JSON field was a better option for our use case, as we stored large amounts of varying data to be only used for retrieval <em>without manipulation</em>.</p><p>Deciding between JSONB and JSON will depend on several factors, such as requirements for indexing, lookups, operations, and retrieval.</p><p><strong>The short answer is,</strong></p><p><strong>Use JSON when:</strong></p><ul><li>You are only storing and retrieving data within this field</li><li>You do not need JSONB’s benefits and would prefer to save write time and disk space</li></ul><p><strong>Use JSONB when:</strong></p><ul><li>You need indexing of keys within the object</li><li>You will perform lookups over this field</li><li>You will perform operations over this field, such as sorting, ordering, or slicing, before working with the representation in your application [2].</li></ul><h3>Switching from JSONB to JSON</h3><p>If you’re using Postgres with Django and importing the JSONField object, you’re using JSONB. This is the default in recent Django versions and is a sensible choice for most applications, but you may find that you’d prefer a standard JSON based on your data and workflow.</p><p>If you find that you don’t need JSONB’s features, you have two options:</p><ol><li>You can use a text field, which will store your JSON in the exact input format. There are a few caveats to this approach:</li><li>You will need to serialize and deserialize the object when working with it, especially in an API context</li><li>A native text field does <em>not</em> provide JSON input validation. To ensure that you’re storing valid JSON objects, you’ll need to validate this before inserting it into your database.</li><li>You will not be able to retroactively cast the field to a jsonb if you later decide to use JSONB format.</li><li>If you want the convenience of a package, you can use packages like <a href="https://pypi.org/project/django-jsonfield/">django-jsonfield</a> or <a href="https://pypi.org/project/jsonfield/">jsonfield</a>, which will handle validation and serialization by default. If you opt-out of using JSONB, this is the preferred option.</li></ol><p>If you’re using other databases like MySQL, you may opt for a package like <a href="https://pypi.org/project/django-mysql/">django-mysql</a>, which provides support for JSON fields and extends the functionality of MySQL in your Django application.</p><h3>Using JSON with Django Rest Framework</h3><p>To solve the performance issue, we opted to switch to using the JSONField field provided by <a href="https://pypi.org/project/django-jsonfield/">django-jsonfield</a>, allowing us to remove JSONB from the model entirely. With our new JSON fields, we suddenly found that the data provided by our API to our processing/job service was causing exceptions when we were attempting to extract and load information from the object. Where we originally were inferring a native JSON object, which was already deserialized by Django, we instead were receiving a JSON object in the form of a string. Our data providers didn’t expect this and quickly began failing when we attempted to use any metadata from our API.</p><p>After some experimentation, we found that responses needed to have these new JSON fields deserialized manually before being returned in the API. Django handled this originally, but switching to a non-default field required some adjustment.</p><p>Assuming that you’re using serializers within Django Rest Framework (DRF), you can update the serializer for the field to be a <a href="https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield">SerializerMethodField</a>, which can be used to add any arbitrary data to your object’s serialized representation or change the representation of an existing field. Here’s how you can deserialize the JSONField within a serializer:</p><pre>from rest_framework import serializers<br>from rest_framework.fields import SerializerMethodField</pre><pre>from models.cluster import Cluster</pre><pre>class ClusterSerializer(serializers.ModelSerializer):<br>  metadata = SerializerMethodField()</pre><pre>  class Meta:<br>    model = Cluster<br>    fields = [&quot;metadata&quot;]</pre><pre>  def get_metadata(self, obj):<br>    return obj.metadata</pre><p>This forces the field to deserialize from a string to a Python dict. If you intend on using this field in more than one serializer, you may benefit from adding a property to the model to automatically deserialize this field instead of within your serializer:</p><pre>from django.db import models</pre><pre>import jsonfield</pre><pre>class Cluster(models.Model):<br>  metadata = jsonfield.JSONField()</pre><pre>  @property<br>  def _metadata(self):<br>    return self.metadata</pre><h3>Further anecdotes</h3><p>Admittedly, there were too many confounding factors relating to this issue to blame for the usage of the JSONB field. Because we had resolved the problem with this change, I stopped researching possible causes beyond what I had originally found and stopped looking further into performance benchmarks.</p><p>Jobs in this table and the corresponding column were being populated by data produced through a disconnected processor. The output had been sent through our API at the time (this has since changed as another performance consideration), and inserts were being handled by our main Django application.</p><p>Based on our usage, there may have been issues with indexing, or the query planner was somehow unable to work with the data in this column across all of our jobs. As we experiencing slowdowns both in our application and using an RDBMS, I’m unsure if this was amplified by passing the model to a DRF serializer, which has an overhead of its own; or if our managed database simply could not handle returning this data as part of our queries.</p><p>Interestingly, we had millions of rows in another table that had five times the number of JSONB columns with no obvious differences in performance. These JSONB columns were fully queryable and responded in a reasonable amount of time, concerning the size of the data being returned, despite no difference in the model’s definition of the JSON field. Many of these columns had significantly more data than the related column in any of the problematic jobs, and yet they were handled significantly better by the RDBMS. Our problematic table with only a few rows took up around 16MB of space, whereas switching to a normal JSON reduced table size to a few KB. The table with millions of rows and sets of JSONB columns held 20GB+ of data and responded within seconds to both complex and simple queries.</p><p>While this change likely isn’t the single reason behind performance improvement, it helped recognize that there is a need to make considerations about how you’re storing and handling related data. As our system matured and we had more examples of what distinct outputs of these jobs may look like, we eventually normalized this report column into its separate table, allowing us to improve performance even further by lazily loading report data while keeping our API less complex. After reviewing the output of several distinct jobs, we extracted upwards of 20 attributes into dedicated columns with explicit data types, which will help significantly with performance over time as the size of the data stored in this table continues to grow.</p><p>I don’t have the full answer to what happened here, as I didn’t get to spend more time investigating. If you have any thoughts on what may have occurred beyond what I’ve covered here or have experienced this yourself, <a href="/service/mailto:roman@romansorin.com?subject=A+note+on+JSONB">I’d love to chat</a>.</p><h3>Footnotes</h3><p>[1] Operations here refer to things like search, sorting, slicing, and ordering done directly through database queries.</p><p>[2] “Working with the representation in your application” refers to retrieving your object from the database, storing it in memory/as a local variable, and then working with the local object. At this point, it wouldn’t matter what format the JSON is stored in, as you’ll only get JSONB benefits when operations are done within the database context.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93478738b887" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deleting Git branches in bulk]]></title>
            <link>https://medium.com/@romansorin/deleting-git-branches-in-bulk-643f625f87ae?source=rss-31f2eb794f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/643f625f87ae</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Roman Sorin]]></dc:creator>
            <pubDate>Tue, 08 Mar 2022 23:59:33 GMT</pubDate>
            <atom:updated>2022-03-08T23:59:33.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkENgBOpbajo6t3nyNulaQ.png" /><figcaption>Deleting Git branches in bulk</figcaption></figure><p>Deleting several Git branches at once with commands like git branch -D can become a real headache. At any time, I have between 5-15 branches per project, all of which I may complete at random times based on priority and state. If you forget to delete your local branches after merging your work, you may end up having weeks of stale branches living within your project.</p><p>Thankfully, there’s an easier alternative to this, and we can run a single command using commands like a pipe (|) and grep to delete several branches at once.</p><h3>The command</h3><p>Deleting branches in bulk can be done in a single line:</p><pre>git branch | grep -iE &#39;FIX|FEAT&#39; | xargs git branch -D</pre><p>Let’s take a look at what’s being done here:</p><ol><li>First, we define our first command, git branch, on the left side of the first pipe. This lists all of the branches within your project.</li><li>Second, we define a grep command which will search the output of our branch command. Since we are using a pipe, the output of git branch is passed to grep. To match several branch patterns at once, we define the -E flag. This allows us to match several strings while also supporting extended regular expressions. We also may have case variations between “FIX”, and “fix”, meaning our grep should be case-insensitive. We do this with the -i flag.</li><li>Third, we define the normal branch deletion command on the right side of the last pipe, and also supply xargs as part of this command. xargs, or extended arguments, will take the left side of the last pipe (our grep command) and pass it as arguments to git branch -D, calling the branch deletion command for each matched branch.</li><li>As a result, all branches that start with “FEAT” or “FIX” (case insensitive) are automatically deleted.</li></ol><h3>Visualizing the deletion</h3><p>To visualize this, let’s run each of these commands individually:</p><pre>$ git branch</pre><pre>FEAT/RS-123<br>FIX/RS-456<br>IMPROV/RS-13<br>feat/RS-96<br>fix/RS-56<br>REF/RS-250</pre><p>Running git branch returns all of the existing local branches. Now, let’s try to find all of the branches that we want to delete:</p><pre>$ git branch | grep -iE &#39;FIX|FEAT&#39;</pre><pre>* FEAT/RS-123<br>* FIX/RS-456<br>* feat/RS-96<br>* fix/RS-56</pre><p>Our grep command highlighted the matching branches and each matched phrase. Using the pipe operator, we passed the output of git branch into the grep.</p><p>If we typed the deletions manually for each branch, instead of using the full command, it would look something like this:</p><pre>$ git branch -D FEAT/RS-123<br>Deleted branch FEAT/RS-123 (was 1b39b22).</pre><pre>$ git branch -D FIX/RS-456<br>Deleted branch FIX/RS-456 (was ea9973f).</pre><pre>$ git branch -D feat/RS-96<br>Deleted branch feat/RS-96 (was 6c114fb).</pre><pre>$ git branch -D fix/RS-56<br>Deleted branch fix/RS-56 (was 5a82faa).</pre><p>We can now see that instead of a single command that takes advantage of pipes, we had to type 6 different commands, each of which has a standard output of its own — making it tougher to keep track of what was deleted, and what still needs to be cleaned up.</p><h3>Passing data using pipes</h3><p><a href="https://www.man7.org/linux/man-pages/man2/pipe.2.html">Many resources exist</a> on pipes and their usages, but it may help to visualize usage in the context of deleting this branch deletion command. In our case, the condensed data flow looks something like this:</p><pre>git branch -&gt; grep -iE &#39;FIX|FEAT&#39; -&gt; xargs git branch -D</pre><p>Each side of our pipe has a “standard input” (STDIN) and “standard output” (STDOUT). The STDOUT is the result of running a command and is passed in as STDIN to the next command. In our flow:</p><pre>git branch (STDOUT) -&gt;<br>(STDIN) grep -iE &#39;FIX|FEAT&#39; (STDOUT) -&gt;<br>(STDIN) xargs git branch -D (STDOUT)</pre><p>While this is an overly simplistic explanation of what is happening behind the scenes, it hopefully provides an idea of how commands and their outputs can be spliced together using pipes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=643f625f87ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Disabling the Tailwind input ring]]></title>
            <link>https://medium.com/@romansorin/disabling-the-tailwind-input-ring-4d6b8484788e?source=rss-31f2eb794f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d6b8484788e</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[tailwind]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Roman Sorin]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 13:41:11 GMT</pubDate>
            <atom:updated>2022-06-28T22:57:43.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ICXM4XdrkqPeNufI7mDoEQ.png" /><figcaption>Disabling the Tailwind input ring</figcaption></figure><p>If you’ve ever worked with <a href="https://tailwindcss.com/">Tailwind</a> components or <a href="https://tailwindui.com/">TailwindUI</a>, you’ve probably come across the “focus ring”. On inputs (checkboxes, fields, etc.), this ring is shown when you’ve clicked or tabbed onto a component, indicating that you have selected it. Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/28/0*XPgi7-KQer3tEhTd.png" /></figure><h3>Disabling the ring</h3><p>I’ve seen myself and others try to disable this by simply calling the focus:ring-0 utility. This sort of works, but gives us this weird shadowing effect on the corners of our input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/24/0*6xjfMSo5ML6MwWxb.png" /></figure><p>By default, Tailwind will include this ring and an offset on certain input elements like checkboxes. If you’d rather not have this ring on all interactions, you can easily disable it:</p><pre>&lt;input type=&quot;checkbox&quot; className=&quot;focus:ring-0 focus:ring-offset-0&quot; /&gt;</pre><p>With this, we’re able to get a nice looking checkbox, without the “ugly” looking ring:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/0*FNgo1HF2TQDMj2ww.png" /></figure><h3>Keeping things clean</h3><p>To reduce redundancy across my project, I created a class that I can globally apply:</p><pre>.without-ring {<br>  @apply focus:ring-0 focus:ring-offset-0;<br>}</pre><p>Now, instead of re-defining these utilities on all of my inputs, I can use the without-ring class to achieve the desired output:</p><pre>&lt;input type=&quot;checkbox&quot; className=&quot;without-ring&quot; /&gt;</pre><h3>Keeping it accessible</h3><p>Accessibility is important, but to keep it short, I won’t cover it here. Instead, <a href="https://medium.com/hackernoon/removing-that-ugly-focus-ring-and-keeping-it-too-6c8727fefcd2">this post by David Gilbertson</a> provides a simple, framework-agnostic solution to showing the focus ring only when a user is tabbing and making it hidden otherwise.</p><p>Keeping it within Tailwind, we can use both our pre-defined without-ring class and native CSS selectors to show the ring for keyboard users, but hide it when using a mouse:</p><pre>.without-ring:focus:not(:focus-visible) {<br>  @apply focus:ring-0 focus:ring-offset-0;<br>}</pre><pre>.without-ring:focus-visible {<br>  @apply ring-2 ring-offset-2;<br>}</pre><pre>// If we wanted to apply this globally, we could use native type selectors</pre><pre>[type=&quot;checkbox&quot;]:focus:not(:focus-visible) {<br>  @apply focus:ring-0 focus:ring-offset-0;<br>}</pre><pre>[type=&quot;checkbox&quot;]:focus-visible {<br>  @apply ring-2 ring-offset-2;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d6b8484788e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cherry-picking done easy]]></title>
            <link>https://medium.com/@romansorin/cherry-picking-done-easy-de8c7748216c?source=rss-31f2eb794f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/de8c7748216c</guid>
            <category><![CDATA[developer-productivity]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Roman Sorin]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 19:08:34 GMT</pubDate>
            <atom:updated>2022-02-01T13:26:14.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHOPAFrx3L1tPWimTo2rsQ.png" /><figcaption>Cherry-picking done easy</figcaption></figure><p>Have you ever needed to cherry-pick several commits between two branches, but ran into conflicts every time? I made this mistake myself — but cherry-picking doesn’t have to be hard.</p><p>As you work on more features and fix more issues, some might not be released immediately. When moving code between environments, you may need to move specific changes over, even if they live alongside other things that you’ve written. This is where cherry-picking comes into play, and if you’ve ever worked in any type of git-flow, you’ve probably come across it.</p><h3>Strategies to the rescue</h3><p>Merge strategies allow you to define how to apply commits from one branch to another. By default, the cherry-pick strategy is <a href="https://git-scm.com/docs/git-merge#Documentation/git-merge.txt-recursive">recursive</a>. Depending on what base branch you’re working off of, you’ll want to use the correct merge strategy for specifying what changes to use: this is where -X=theirs and -X=ours do us favors.</p><h3>Performing the cherry-pick</h3><p>The cherry-pick command is simple:</p><p>git cherry-pick --strategy=recursive -X=theirs hash0 hash1 hash2</p><p>You’re able to specify the strategy, the per-strategy option (theirs/ours), and the sequence of hashes (commits) to merge.</p><blockquote>What is the difference between theirs and ours?</blockquote><p>This option will specify which version of code to prefer in a merge. If you’re on the main branch and moving commits from develop, you’ll want to use <em>theirs</em>, as you are saying “let’s take develop’s (their) changes”.</p><p><strong>What you’ll need:</strong></p><ul><li>A base and target branch (develop/main)</li><li>The commit hashes to cherry-pick (e.g. 7f7a499)</li><li>Choosing the right strategy based on what you want to achieve (ours/theirs)</li></ul><p>For example, to merge a sequence of commits from a development branch into main:</p><ol><li>Check out the main branch with git checkout main.</li><li>Using the cherry-pick command from above, we will merge several develop commits to our main branch, moving the develop changes onto main. You can specify the hashes individually, or you can cherry-pick a sequence of hashes by writing hash0...hash1.</li><li>If conflicts come up, you’ll be able to resolve them on a per-commit basis and commit the result to continue with your cherry-picking.</li></ol><p>Although simple, learning this has turned large merge requests that affected over 40 files (including deletions, renames, and refactors) into a pain-free experience instead of a major ordeal. Something that would’ve taken me several hours with the potential of missing code only took an hour, and shortly thereafter, I was able to move on to working on my next task.</p><p>This isn’t all that cherry-pick has to offer, and there are flags for you to provide based on your use case. If you need something beyond this or if you want to read a little bit about how cherry-picks are done, the <a href="https://git-scm.com/docs/git-cherry-pick">Git docs</a> do a great job of explaining this concept.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de8c7748216c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hiding primary keys and database IDs using Hashids]]></title>
            <link>https://medium.com/@romansorin/hiding-primary-keys-and-database-ids-using-hashids-4386f713ec15?source=rss-31f2eb794f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/4386f713ec15</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Roman Sorin]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 13:12:47 GMT</pubDate>
            <atom:updated>2021-11-30T00:36:34.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Hiding primary keys and database IDs using Hashids" src="https://cdn-images-1.medium.com/max/1024/1*WbXEEMCE_RT4M-XxgdQqCQ.png" /><figcaption>Hiding primary keys and database IDs using Hashids</figcaption></figure><p>In most CRUD operations and REST APIs, primary keys are used to reference models that you want to access or modify. A majority of APIs will take an ID as a parameter in a route:</p><pre>GET /api/v1/posts/:id</pre><pre>// Return the Post resource with an ID of 457<br>GET /api/v1/posts/457</pre><p>While it’s the simplest and most effective way of specifying the model to use, we often don’t want to show these IDs to the user. By displaying primary keys, you give users the ability to estimate the number of rows in your tables. If authorization isn’t effective or routes aren’t protected, users could input random numbers to access information that they otherwise shouldn’t have.</p><p>Using obfuscated IDs can be useful in social media or feed contexts, where the content isn’t used in the URL, but you want something less significant than a primary key. As an example, instead of showing the user a URL like this:</p><p><a href="https://romansorin.com/posts/457">https://romansorin.com/posts/457</a></p><p>We may want to show them something like this instead:</p><p><a href="https://romansorin.com/posts/akz1JV">https://romansorin.com/posts/akz1JV</a></p><p>In this case, you may want to use “hashes” as a way to obfuscate your ID. We’ll use the lightweight <a href="https://hashids.org/">Hashids</a> package to make this happen.</p><h3>Installation</h3><p>Getting started with Hashids is simple. With your preferred package manager, add Hashids to your project:</p><pre># If you use yarn as a package manager<br>yarn add hashids</pre><pre># Or if you use npm<br>npm install hashids</pre><h3>Usage</h3><p>I’ve provided a Javascript example to begin working with Hashids, but Hashids has <a href="https://hashids.org/">support for several languages</a>! Here’s a brief use case, where you may want to hide the ID of a post:</p><pre>import hashids from &quot;hashids&quot;;</pre><pre>// Two arguments supplied: a salt and a minimum padding (length)<br>const postHash = new hashids(&quot;post&quot;, 8);</pre><pre>const post = { id: 4 };<br>post.id; // 4</pre><pre>const hashedPostId = postHash.encode(post.id);<br>hashedPostId; // 6akz1JVq<br>postHash.decode(hashedPostId); // [4]</pre><p>Here, we’re importing the hashids package and creating an instance of the module, calling it postHash.</p><p>I set up a dummy post object, but you can use any object or ID that you see fit. Due to package limitations, the argument supplied to the module <em>must be an integer</em>. Strings and objects cannot be obfuscated using Hashids.</p><p>Afterward, I supplied the ID into the encode function of the postHash object and then put this output back through the decode function to show how you can use encoding/decoding. Note that the return type of decode is an array, <em>not</em> an integer.</p><p>If that’s all you’re looking for, then that’s it! You can also encode and decode multiple IDs at once:</p><pre>const hashes = postHash.encode([1, 2, 3]);<br>postHash.decode(hashes); // [1, 2, 3]</pre><h3>Bonus: A utility class</h3><p>If you want a common utility to work with, <a href="https://gist.github.com/romansorin/c25e8cbe132ae34bf19ee91e5926a364">here is an abstraction</a> on top of the Hashids package that will allow you to encode and decode IDs easily, without having to remember the package’s methods.</p><p>This class is limited to encoding/decoding a single ID at a time but it helps me stay consistent within my projects. By using this utility, you could also set up a file/store of your hash objects, so you don’t have to redefine it across your application:</p><pre>// lib/Hash.ts<br>const Hashids = require(&quot;hashids/cjs&quot;);</pre><pre>export class Hash {<br>  private hashids;</pre><pre>  /**<br>   * Creates a Hash object.<br>   *<br>   * @param {string} salt The unique salt/alphabet to use for salting. Setting a salt allows output hashes to be more unique.<br>   * @param {number} padding The minimum output length of the hash (default is 6).<br>   */<br>  constructor(salt: string = &quot;&quot;, padding: number = 6) {<br>    this.hashids = new Hashids(salt, padding);<br>  }</pre><pre>  /**<br>   * Encodes the provided ID argument and returns a string representing the hash.<br>   *<br>   * @param {number} id The numeric &quot;id&quot; to be encoded or turned into a hash.<br>   * @returns {string} Returns the encoded ID in the form of a hash, e.g. &quot;o2fXhV&quot;<br>   */<br>  public encodeId(id: number) {<br>    return this.hashids.encode(id);<br>  }</pre><pre>  /**<br>   * Decodes the provided hash argument and returns a number representing the ID.<br>   *<br>   * @param {string} id The numeric &quot;id&quot; to be encoded or turned into a hash.<br>   * @returns {number} Returns the numeric ID, e.g. &quot;1&quot;<br>   */<br>  public decodeId(hash: string) {<br>    const decoded = this.hashids.decode(hash);<br>    return decoded.length &gt; 1 ? decoded : decoded[0];<br>  }</pre><pre>  /**<br>   * Sets the internal hashids object with the provided salt/padding arguments.<br>   *<br>   * @param {string} salt The unique salt/alphabet to use for salting. Setting a salt allows output hashes to be more unique.<br>   * @param {number} padding The minimum output length of the hash (default is 6).<br>   */<br>  public setHashids(salt: string = &quot;&quot;, padding: number = 6) {<br>    this.hashids = new Hashids(salt, padding);<br>  }<br>}</pre><p>Using this utility class is as simple as the native Hashids package. The implementation stays largely the same, but may be more readable and easy to remember:</p><pre>const { Hash } = require(&quot;@lib/Hash&quot;);<br>const { Post } = require(&quot;@app/models/Post&quot;);</pre><pre>// Create a new Hash object with the salt &quot;post&quot;<br>const postHash = new Hash(&quot;post&quot;, 8);</pre><pre>// We may want to generate different sequences based on model, to get different values for the same ID<br>const userHash = new Hash(&quot;user&quot;, 8);</pre><pre>post = new Post();<br>post.id; // 4</pre><pre>const hashedPostId = postHash.encodeId(post.id);<br>hashedPostId; // 6akz1JVq<br>postHash.decodeId(hashedPostId); // 4</pre><pre>// Want to change the salt of the Hash object without creating a new object?<br>// Call &quot;setHashids&quot; through the utility function.<br>postHash.setHashids(&quot;comment&quot;, 8);<br>postHash.decode(hashedPostId); // Now, it returns undefined instead of 4</pre><pre>// With a different salt, we can use the old Post ID and get a different value:<br>const hashedUserId = userHash.encodeId(post.id);<br>hashedPostId; // dD0WnjRy</pre><p>This example is a little bit more extensive, so let me walk you through it:</p><ol><li>We created two hash objects to represent a Post and User model.</li><li>Like the previous example, I created a dummy Post object with an ID of 4.</li><li>I passed the ID into the encode function (of the custom utility) and then decoded it, which was the same as the previous example.</li><li>The utility allows you to set a new salt and padding within the same object instance, so I changed the salt to “comment”. Now, when you try to decode the previous hash, you don’t get the same ID.</li><li>Since the userHash object had a different salt, encoding the previous ID returns a completely different hash.</li></ol><p>Unfortunately, a limitation of this utility is that you can’t encode or decode multiple IDs at once, but this can be easily added in by extending the class functions. When developing a medium-scale app with the Hashids library, I found this utility to be super useful in keeping my code consistent across controllers.</p><h3>Limitations</h3><p>It’s worth noting that Hashids should not be used as a legitimate hashing solution (such as passwords or other encrypted information). The Hashids package doesn’t have support for strings anyway, but you shouldn’t even consider this — instead, use an algorithm like <a href="https://auth0.com/blog/hashing-in-action-understanding-bcrypt/">bcrypt</a> to encrypt your sensitive data.</p><p>Additionally, as the package creator describes, these aren’t true “hashes”. Cryptographic hashes cannot be decrypted, but the output looks similar which results in this obfuscation being considered a “hash”.</p><h3>More robust strategies</h3><p>When I was looking into packages and solutions to masking IDs in an application of my own, my first thought was to look into what companies like <a href="https://instagram-engineering.com/sharding-ids-at-instagram-1cf5a71e5a5c">Instagram</a> and <a href="https://blog.twitter.com/engineering/en_us/a/2010/announcing-snowflake">Twitter</a> were doing. I noticed that despite the volume of data that is processed on these platforms, they didn’t resort to using primary keys for their URLs. If you’re interested in how they handled this ID generation (hint: it wasn’t Hashids!), I would highly suggest reading the articles I linked above.</p><p>In the <a href="https://www.notion.so/Hiding-primary-keys-and-database-IDs-using-Hashids-7257783fd3e44ad6acf3914c25cac910">Medium post</a> documenting Instagram’s solution, the URL contains yet another example of hashes being used in the URL: first the slug of the article, and then a sequence of random characters after to maintain uniqueness.</p><p><a href="https://instagram-engineering.com/sharding-ids-at-instagram-1cf5a71e5a5c">https://instagram-engineering.com/sharding-ids-at-instagram-1cf5a71e5a5c</a></p><p>In a content-heavy context where the title of a post may be significant (blogs or forums), this approach keeps the URL significant but also minimizes the chance of collisions by keeping records unique.</p><p>Hashids is an effective approach for a small to medium-scale application that doesn’t require more complicated strategies like combining different metadata (creation date, worker/sequence count, shard IDs). While it doesn’t fit data or scale-intensive cases like Twitter, regular applications that process a reasonable amount of writes will do just fine with this approach. Collisions can be avoided by choosing unique salts for each model that you obfuscate and an appropriate minimum length (at least 8 characters).</p><p><em>Originally published at </em><a href="https://romansorin.com/blog/hiding-primary-keys-and-database-ids-using-hashids"><em>https://romansorin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4386f713ec15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zillow’s confusing keyword UX]]></title>
            <link>https://medium.com/design-bootcamp/zillows-confusing-keyword-ux-e04d82b2c1fb?source=rss-31f2eb794f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/e04d82b2c1fb</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Roman Sorin]]></dc:creator>
            <pubDate>Wed, 27 Oct 2021 02:25:58 GMT</pubDate>
            <atom:updated>2021-11-30T00:35:50.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Zillow’s confusing keyword UX" src="https://cdn-images-1.medium.com/max/1024/1*hLegATio-wdKAO7jDApuTw.png" /><figcaption>Zillow’s confusing keyword UX</figcaption></figure><p><a href="https://zillow.com/">Zillow</a> has consistently been one of the most popular real estate marketplaces for several years, and for good reason — Zillow has dominated the space for buying and selling homes, as well as listing rentals and providing home loans for prospective buyers. While searching for apartments this summer (and as I’m planning to buy a home), I used Zillow almost exclusively to explore options and contact properties.</p><p>Almost <a href="https://www.nar.realtor/sites/default/files/documents/2019-profile-of-home-buyers-and-sellers-highlights-11-21-2019.pdf">half of all people</a> searching for homes start by looking online before contacting a local realtor. Despite the amount of information that searchers have immediately at their disposal, finding a property is nothing like a product on Amazon. Homebuyers using Zillow and similar platforms spent, on average, ten weeks searching for homes; those who took traditional routes spent closer to four weeks.</p><p>This brings us to one of the key features in any search or commerce context: filtering. For being such a large name in the real estate space, it’s hard to believe that the options for filtering are so primitive. Filtering is limited to specifying a price range, beds/baths, and other basic features, but almost nothing more. As you use the platform, you have to potentially spend hours trying to find properties that fit your criteria. While this increases engagement, you end up frustrating the user.</p><p>Intuitively, you would expect the “keywords” field to give you more control of what you’re looking for. The ability to specify certain words or phrases is convenient, especially when you’re looking for a certain style of home or other qualitative traits beyond the generics. With so much information attached to listings, it’s surprising that there isn’t a more developed way of finding this deeper engrained yet relevant information.</p><p>With this, let’s explore the keywords field: what it gets right, how it can improve, and how other platforms can change the approach to home searching.</p><h3>What they get right</h3><p>From the input, it’s clear that they expect you to input keywords as a comma-delimited list. After you’ve finished and clicked “Done”, your list of results decreases. This is expected behavior but doesn’t offer much feedback. Zillow isn’t alone in this behavior — another well-known marketplace, <a href="https://redfin.com/">Redfin</a>, also has the same “keywords” field that functions similarly.</p><figure><img alt="Zillow’s keywords field" src="https://cdn-images-1.medium.com/max/537/0*FVla26XhcxrqoXpi.png" /><figcaption><em>The keywords input is clear as it’s comma-delimited and gives examples of what it’s looking for.</em></figcaption></figure><p>Without trying several cases to see how the search performs, it’s difficult to see how the keywords field works. After trying several sequences of keywords (“open”, “open, modern”, “open, modern, pool”), I found that it matches each keyword and works as a strict filter, rather than evaluating each keyword individually.</p><p>This works, and once you understand it, functions as expected. But it’s kind of useless.</p><h3>Complex queries aren’t possible</h3><p>To start, I made a baseline search around Dallas, TX:</p><pre>Price Range: $400k-$1m <br>Home Type: Single-family, for sale <br>3+ beds, 2+ baths </pre><pre>Results: 5,964 listings</pre><p>This yielded 5,964 listings which is a healthy number to filter down. At this point, <em>any</em> home matching these criteria will be returned and doesn’t take other features into account.</p><p>As mentioned before, I’m using a combination of phrases such as “open, modern, pool” to evaluate how filtering works with this field and what it potentially misses.</p><p>Here are the results of using different combinations of these phrases to illustrate how big of an impact the keywords field has on search results:</p><pre>Listings by keyword: </pre><pre>&quot;Open&quot;: 2,749 <br>&quot;Pool&quot;: 1,273 <br>&quot;Open, Pool&quot;: 502</pre><p>A single keyword significantly reduces the number of results and hopefully can filter out non-matching properties. However, this field is only useful if the information is available and it takes the <em>correct</em> information into account.</p><h3>Wildly inaccurate</h3><p>With a little bit more investigation on my baseline query, I decided I’d try to test the accuracy of the keywords field. As an example, I entered “3 bed” into the field on its own, which reduced the number of results to 162 listings. This seems somewhat promising, yet my first result was a four-bedroom house. Even if I’m allowing more than three bedrooms in my base query, properties matching the keyword should be returned first. What gives?</p><figure><img alt="Keywords field with “3 bed” specified" src="https://cdn-images-1.medium.com/max/1024/0*F6in1RgvnqrGET66.png" /><figcaption><em>Just supplying “3 bed” as the phrase for the keywords returns 162 listings, opposed to the original 5,964.</em></figcaption></figure><p>I looked throughout the listing to find any mention of “3 bed” or the number 3 at all. All I could find was the “3 CAR GARAGE” tag, which is not even contextually relevant.</p><figure><img alt="A listing found under the “3 bed” keyword, but there is no mention of 3 bed on the listing itself" src="https://cdn-images-1.medium.com/max/1024/0*BkmtODi86F9OoDjd.png" /><figcaption><em>With “3 bed” in the keywords input, this listing is returned — but the description has no mention of “3 beds” (only “3 car garage”), and the house itself has 4 bedrooms.</em></figcaption></figure><p>I looked to see what the sorting options were for results to see if there was a “Relevance” option. Nothing would change the results appropriately to what I wanted, despite being a very basic filter. The nearest option is “Homes for You”, which is supposedly determined based on the homes you’ve viewed and your prior searches, but I don’t want a feed — I want better search results. Yes, there is a dedicated filter functionality for choosing the number of beds you want to have returned, but this result speaks volumes on the limitations of filtering.</p><figure><img alt="A dropdown of the listing results sorting options, with “Homes for You” selected" src="https://cdn-images-1.medium.com/max/727/0*otNT2emiKC0kc6ap.png" /><figcaption><em>Zillow offers different types of sorting options, but nothing to do with search relevancy beyond “Homes for You”.</em></figcaption></figure><p>It’s evident that when the filter does work, it seems to only search the description of the listing. This leaves out a lot of valuable information, especially if the description is incomplete, or if the relevant data is in some other property of the listing. Despite the number of attributes that can be filled out for a listing, these are very loosely compared against the keywords input.</p><p>For final verification of the attributes that are likely considered, I searched the “Parcel Number” that was found under a property listing in the keywords (Zillow gives an example of “MLS #” in their input, so I figured other IDs would be supported), and that listing could no longer be found. While I don’t know how their data is modeled, I believe they could instead do a more exhaustive, comprehensive search over the listing with proper indexing.</p><h3>A better way of home searching</h3><p>From testing, it seems that keywords are all evaluated as a strict filter, meaning that they are matched directly against. I didn’t see support for fuzzy text searching (i.e. misspelling a keyword may return zero results), and the “3 bed” experiment showed that there is no contextual relevancy.</p><p>On Zillow and other platforms, it would be nice if you could input a more generic search term or phrase that allowed for more specificity. There may not be a huge market need for it, but it could potentially be a major help to people who want to find homes that are aligned with their needs, without having to reach out to realtors and agents. I haven’t come across a real estate listing site that operates as a search engine — while it’s a lot to ask, it would offer homebuyers a faster path to finding candidate homes that they might want.</p><p>Aside from working with a realtor, it can be tough to find exactly what you want without spending a lot of time looking at options. Even if you’re casually browsing, it can be frustrating to have a massive list of potentially irrelevant options shown to you, especially if you know what you’re looking for.</p><p>I briefly explored this issue earlier in the year while developing an MVP for a small-time project of mine called <a href="https://abodelistings.com/">Abode</a>. The model for home searching has been consistent for years, but that doesn’t necessarily mean it works well, especially as usage patterns evolve.</p><p>While drafting ideas on how to solve some of these problems, I came across an <a href="https://www.zillow.com/tech/improve-quality-listing-text/">article written by Zillow</a> which explored improving results by putting the listing’s description through an embedding model paired with existing recommender systems. The article states that Zillow uses different features of the listing “to build recommendations on similar homes, personalized search rankings, and other personalization systems for customers”, so it seems that much of this recommendation is done behind the scenes, without the user being aware of it. It’s a bit ironic that their behind-the-scenes systems seem to be well-thought-out, but their search functionality is so primitive — despite being the point of entry for users looking to find a home.</p><p>It seems like <a href="https://www.zillow.com/tech/personalized-search-refinements/">Zillow is working on solutions</a> to solve this through their existing filters, which looks to be based on localized demand (on-site parking, allowing pets in complexes, etc.) — but still haven’t offered a solution to more “fuzzy” suggestion. Using embeddings and making predictions based on provided phrases seems like a great solution to improving search quality and allowing for a more attractive search process. While I’m doubtful Zillow will solve this problem themselves, it could be an attractive offering if a new platform presents itself.</p><h3>But is it necessary?</h3><p>Admittedly, it might not be solving all that large of a problem. After looking at various results on Google Trends, the most popular searches are things like “new construction houses for sale”, “beach houses for sale”, “manufacturer homes” — results which are easily returned through the dedicated filters. But, if a property listing is incomplete beyond the basic information and a description, information that is important to some people (such as the “view” or certain amenities) may be lost. People searching for apartments, for example, may input several criteria into the keywords field, but don’t expect them all to be matched. Even if they do, too many keywords may return no results. Apps like <a href="https://www.apartmentlist.com/">ApartmentList</a> have solved some of these issues, but it’s less known than Zillow and other platforms.</p><p>Real estate listing sites and aggregators are difficult to do, in some respects. You can’t always have perfect information, especially at scale — but there are ways of solving some of the limitations. The root of this problem seems to be the incompleteness of data. In the future, I would love to see a real estate platform use more advanced concepts, such as <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network">RNNs</a>/ <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">CNNs</a>, to automatically extract features from photos to pre-fill or supplement listings. Building extra layers such as checking image quality, description quality, and providing feedback or predictions on how well a listing may perform may ultimately ease frustrations for a homebuyer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e04d82b2c1fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/design-bootcamp/zillows-confusing-keyword-ux-e04d82b2c1fb">Zillow’s confusing keyword UX</a> was originally published in <a href="https://medium.com/design-bootcamp">Bootcamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design for your developers, not just your users]]></title>
            <link>https://medium.com/design-bootcamp/design-for-your-developers-not-just-your-users-eb3eada7bd1?source=rss-31f2eb794f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb3eada7bd1</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Roman Sorin]]></dc:creator>
            <pubDate>Sat, 16 Oct 2021 14:19:54 GMT</pubDate>
            <atom:updated>2021-11-30T00:32:05.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Design for your developers, not just your users" src="https://cdn-images-1.medium.com/max/1024/1*AjYLTgp8BOeCQSbSjFhKHA.png" /><figcaption>Design for your developers, not just your users</figcaption></figure><p>As a developer, I have worked on many feature definitions, tickets, and mockups. Working on both freelance projects and at companies, I have come across unclear requirements more times than I can count. Though it’s impossible to be perfect, there are ways to improve developer productivity and establish a better foundation for how your apps are built.</p><h3>It starts by designing for your developers.</h3><p>Though users are typically the primary stakeholders, recognize that developers are the bridge between concept and execution. Developers are limited by similar factors; time and budget being two of the most common. However, some limitations are entirely within a designer’s control.</p><p>For example, designs that are overly complex or ambitious can be a nightmare for developers. Even if the design looks eye-catching (think most <a href="https://dribbble.com/">Dribbble</a> shots), it might simply be too difficult to implement or even use. Similarly, developers can perform higher quality work at a much faster rate if there doesn’t need to be a constant feedback-support loop. A developer shouldn’t have to constantly ask what should be displayed in some input case (think failure/success handling), or why two elements are inconsistent in design despite supposedly being the same.</p><p>Here are some basic but common examples of design states that are often forgotten:</p><ul><li>Null/empty values</li><li>New values (reassigning from null)</li><li>In progress, loading, or pending states</li><li>Error, success, etc. Should these be messages? Other visual cues?</li><li>Consistency in implementation, such as text size and color, padding, grid spacing</li></ul><p>While developers should be responsible for making reasonable assumptions and maintaining autonomy, their job is to produce a fluid, functional application from what’s provided. If given something difficult to work with, there’s no guarantee that the actual app will be any better.</p><p>Confusion breeds chaos and makes it tough for many devs — especially those who have little interest or background in design — to accomplish their work in the expected amount of time. For an application to be well-executed, all three points need to interact and consider each other’s needs: designers, developers, and users.</p><p>As a designer, you’re probably dealing with different sets of requirements, communication across different departments, and responsible for designing flows. You may be constrained by deadlines or financial limitations, and so it’s tough. But keep developers in mind, and they’ll return the favor through a beautifully executed user experience.</p><p>In exploring this idea, I found that Invision’s <em>Inside Design</em> <a href="https://www.invisionapp.com/inside-design/design-for-development/">published an article</a> that covered a similar idea. It’s more in-depth and put together than this article, and I highly suggest you read it if this idea interests you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb3eada7bd1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/design-bootcamp/design-for-your-developers-not-just-your-users-eb3eada7bd1">Design for your developers, not just your users</a> was originally published in <a href="https://medium.com/design-bootcamp">Bootcamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My experience of moving from Laravel to Django — Roman Sorin]]></title>
            <link>https://medium.com/@romansorin/my-experience-of-moving-from-laravel-to-django-roman-sorin-c73fc1191edf?source=rss-31f2eb794f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/c73fc1191edf</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Roman Sorin]]></dc:creator>
            <pubDate>Sat, 09 Oct 2021 18:13:54 GMT</pubDate>
            <atom:updated>2021-11-30T00:35:24.519Z</atom:updated>
            <content:encoded><![CDATA[<h3>My experience of moving from Laravel to Django</h3><figure><img alt="My experience of moving from Laravel to Django" src="https://cdn-images-1.medium.com/max/1024/1*ze76PX6gPRdw1KJGxn7W9w.png" /><figcaption>My experience of moving from Laravel to Django</figcaption></figure><p>Before my current role, I spent most of my professional development career writing web apps in <a href="https://laravel.com/">Laravel</a>. I learned Laravel out of necessity after learning PHP, but wanted to avoid working in WordPress — and I quickly grew fond of the framework. Even during Laravel 5, the framework just felt right.</p><p>It was highly opinionated (which was crucial as a new developer, trying to learn the best way to structure large scale, multi-faceted apps), had robust documentation that was extremely easy to follow, and had very clear design patterns that made it easy to interface with the ORM and concepts like Facades. When scaffolding out a new Laravel project, namespaces were clear and it was easy to see how different parts of the app interacted with each other. Laravel’s use of <a href="https://laravel.com/docs/8.x/artisan">Artisan</a> was also a major developer experience boost — you could generate new controllers, models, notifications, and more — without having to rely on any other external tools or questioning if it’s structured properly. It just <em>worked</em>.</p><p>Later on, I moved to using Django as my primary framework. I figured that the transition between Laravel to Django would be simple, but even some of the more basic concepts gave me trouble regarding terminology and patterns.</p><h3>Why Django?</h3><p>Whenever I was looking for new roles at the beginning of 2021, I ended up interviewing for a company (where I currently work) that was using Django as a large part of its stack. Consistently, I was seeing more opportunities for Django and other frameworks revolving around Python and felt that I may have been inhibiting my growth by staying on the Laravel track.</p><p>Even though I had used Flask before in several freelance projects, Django felt like a completely different beast. Flask touts itself as a “micro-framework” and compared to full-fledged frameworks like Django or Laravel, that’s exactly what it is. It’s very convenient for creating more directed projects quickly but falls short with tooling.</p><p>I had a preliminary interview and immediately began learning Django. Despite making it clear that I hadn’t used Django before, I wanted to get as much knowledge of the framework as possible so that I wouldn’t be subject to a major learning curve before beginning my new position.</p><p>I didn’t want to put all of my eggs into one basket, so I kept the sample project I was working on small. It had to be just enough that I covered the major concepts of Django, but with enough complexity that it couldn’t be classified as a “to-do list”. At the time, I wanted a way of tracking inventory in my home office, so I built an incomplete <a href="https://github.com/romansorin/inventory-system">inventory tracking system</a> after following the Django docs. Despite having a <em>lot</em> more experience with the framework now, I still reference this project sometimes when I’m implementing new viewsets (more on this later).</p><p>Side note: If you really want to work at a company and don’t have a solid grasp on the tech that they’re using, pour your time into it (within reason). While it’s perfectly okay to learn on the job (as I did, and still do), being able to hit the ground running and contribute is personally incredibly rewarding.</p><h3>The parallels between Laravel and Django</h3><p>While this won’t be a detailed technical writeup of the two, there are some core concepts that exist in parallel between Laravel and Django. To start, Laravel and Django both follow the <a href="http://www.cs.utsa.edu/~cs3443/mvc-example.html">Model-view-controller (MVC)</a> design pattern, which is a common way of developing both desktop and web applications.</p><h3>Freedom to choose</h3><p>Though they both follow MVC, Laravel feels more “strict” in enforcing certain patterns. If you’ve ever taken a look at the <a href="https://laravel.com/docs/master">Laravel documentation</a> or inside of a Laravel project, you’ll see that there are a lot of different features of the framework that are already abstracted out for you. At a minimum, you run php artisan and generate the components that you need – at maximum, you have to do some configuration to make it fit eloquently into the rest of your app. I use Laravel&#39;s documentation as a gold standard in framework + technical documentation and wish more would follow suit.</p><p>Contrarily, I have always felt that Django gives you a bit more freedom to make your own decisions on how you want to structure your app, what namespaces (module directories) to use, etc. <a href="https://docs.djangoproject.com/en/dev/">Django’s documentation</a> isn’t fantastic compared to Laravel, but it’s enough that you can reference and implement different concepts.</p><h3>Building an API</h3><p>Django also provides you with an “admin” view, which is essentially a CRUD panel for any models that you load. This is probably a better choice for someone looking for a framework with an admin dash prebuilt, but I use both Laravel and Django in the context of building an API only. With Django, you’d need to pull in <a href="https://www.django-rest-framework.org/">Django REST framework (DRF)</a> — Laravel offers it right out of the box.</p><h3>Tinkering with data</h3><p>Both Laravel and Django have a CLI tool that allows you to use parts of your app in isolation and interact with the database. This is really useful when you want to see what certain methods of the query builders do, or one-off functions that would take more writing in a controller/viewset. I personally feel that php artisan tinker is easier to use and integrated more closely with the framework. It&#39;s an incredibly tiny detail, but tinker utilizes autoloading and allows you to reference models by namespaces, without having to import them. This is different from the Django manage.py shell, where you have to import all of the modules and classes that you want to interact with.</p><h3>Where my confusion lied</h3><p>Following the MVC pattern, Laravel and Django both have models, views, and controllers. However, I felt that Django was a lot less clear in designating what maps to what, at least coming from a traditional background. Let me explain:</p><h3>Laravel</h3><p>Two majors concepts of building APIs in Laravel are models and controllers.</p><ul><li>Model: <a href="https://laravel.com/docs/8.x/eloquent">A blueprint for objects</a>, which is just a class that allows you to specify a different table name, primary key, attributes, etc. Unlike Django, defining fields is abstracted away to migration, and Laravel separates the Eloquent instance from the database representation.</li></ul><pre><strong>&lt;?php</strong><br>// App\Models\Employee.php</pre><pre>namespace App\Models;</pre><pre>use Illuminate\Database\Eloquent\Model;</pre><pre>class Employee extends Model<br>{<br>    //<br>}</pre><ul><li>Controller: Typically, <a href="https://laravel.com/docs/8.x/controllers">controllers return model instances</a> with minimal processing. These are where you handle defining CRUD operations for your endpoints (web or API). Unlike Django’s optional functional approach, these are always classes.</li></ul><pre><strong>&lt;?php</strong><br>// App\Http\Controllers\API\EmployeeController.php</pre><pre>namespace App\Http\Controllers\API;</pre><pre>use App\Http\Controllers\Controller;<br>use App\Models\Employee;</pre><pre>class EmployeeController extends Controller<br>{<br>    public function show($id)<br>    {<br>        return response()-&gt;json(Employee::findOrFail($id));<br>    }<br>}</pre><ul><li>Views: <a href="https://laravel.com/docs/8.x/views">Laravel views</a> are Blade templates that are separated from your business logic, and only hold the presentation layer. These are used to display data provided from controllers — the use of “views” is going to be an important distinction in Django, where these are called “templates” in a Django context.</li></ul><p>When defining an API route, you only need to reference the method of an API controller. You don’t need to touch “views” at all, and in a lot of my projects, I never created a single view (I used a separate React/Vue app for this).</p><h3>Django</h3><p>On the other hand, Django uses the concepts of models, serializers, and views (which can be called viewsets). Even for API routes, all three of these are required.</p><ul><li>Model: <a href="https://docs.djangoproject.com/en/3.2/topics/db/models/">The model</a> is similar to Laravel’s definition, but must contain the fields and metadata at a minimum. If you want to define any custom attributes or model-specific business logic, this must be done in a serializer. On one hand, it’s easier to follow and practices better separation of concerns — on the other hand, it’s another file to create, maintain, and reference.</li></ul><pre># app/models/employee.py<br>from django.db import models</pre><pre>class Employee(models.Model):<br>  name = models.CharField(max_length=255)<br>  age = models.PositiveSmallIntegerField(null=True)</pre><ul><li>Serializer: <a href="https://www.django-rest-framework.org/api-guide/serializers/">Serializers</a> are going to be your definition for what a model will return. You have the ability to include/exclude fields from responses, define nested representations (show the entire User model, instead of just a user_id ), and create method fields that will return some value every time your object is being returned. Essentially, splitting a Laravel model returns a Django model + serializer. A serializer is technically an offering of DRF, but if you&#39;re building an API, you&#39;ll have this.</li></ul><pre># app/serializers/employee.py<br>from rest_framework import serializers</pre><pre>from app.models import Employee</pre><pre>class EmployeeSerializer(serializers.ModelSerializer):<br>  class Meta:<br>    model = Employee<br>    fields = [&#39;name&#39;, &#39;age&#39;]</pre><ul><li>Views/viewsets: <a href="https://docs.djangoproject.com/en/3.2/topics/http/views/">Django views</a> are Laravel’s controllers. Here, you can define individual functions (similar to single-action controllers in Laravel), or entire viewsets which hold related methods (controllers). The use of “views” as terminology for a controller was one of the hardest things to wrap my head around. Below is a view <a href="https://www.django-rest-framework.org/api-guide/views/">built using DRF</a>, which differs slightly from a generic Django view.</li></ul><pre># app/views/employee.py<br>from rest_framework import generics</pre><pre>from app.models import Employee<br>from app.serializers import EmployeeSerializer</pre><pre>class EmployeeList(generics.ListCreateAPIView):<br>  queryset = Employee.objects.all()<br>  serializer_class = EmployeeSerializer</pre><ul><li>Templates: The <a href="https://docs.djangoproject.com/en/3.2/topics/templates/">template layer</a> is Django’s presentational “view”. This is where data from your views will be rendered to the user and is analogous to Laravel’s views.</li></ul><h3>The winner</h3><p>There are other design patterns and features that I didn’t dive into here, such as queues and signals/listeners. The usage of both is very different between Laravel and Django, where Django feels more primitive, but that flexibility is what makes it a great choice for many applications. Some may feel that Laravel is too opinionated or enforces too many rules, but that’s what’s great about it — it’s hard to break out of the design pattern, which makes code more consistent and makes it easier to onboard new developers onto a project.</p><p>Personally, I reach for Laravel’s ideas in every project, regardless of what language I’m using. The structure/flow is easy to follow and the documentation is fantastic. When I was using Laravel professionally, I enjoyed it <em>a lot</em>. Being able to use queues, caching, events, and notifications right out of the box made it easy to develop complex features without thinking about what other tools I’d have to pull in. There’s a little bit more work involved with Django, but you also get to define your own starting point and make decisions how you see fit. In terms of performance, <a href="https://fullscale.io/blog/django-vs-laravel-performance-comparison-of-web-application-frameworks/">Django is probably a better choice</a>, but everything comes down to what you need in an application.</p><h3>tl;dr</h3><p>Laravel adheres more closely to traditional MVC — models define business logic and attributes, controllers are used for endpoints and data manipulation, and views provide the presentation layer.</p><p>Django increases complexity a bit by using different terminology — a traditional “model” is essentially a model + a serializer, views/viewsets are traditional controllers, and templates are traditional “views” that provide presentation.</p><p><em>Originally published at </em><a href="https://romansorin.com/blog/my-experience-of-moving-from-laravel-to-django"><em>https://romansorin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c73fc1191edf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling bulk update or create on Django models through filters — Roman Sorin]]></title>
            <link>https://medium.com/@romansorin/handling-bulk-update-or-create-on-django-models-through-filters-roman-sorin-1741184dc30?source=rss-31f2eb794f49------2</link>
            <guid isPermaLink="false">https://medium.com/p/1741184dc30</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Roman Sorin]]></dc:creator>
            <pubDate>Thu, 07 Oct 2021 02:03:45 GMT</pubDate>
            <atom:updated>2021-11-30T00:34:58.923Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling bulk update or create on Django models through filters</h3><figure><img alt="Handling bulk update or create on Django models through filters" src="https://cdn-images-1.medium.com/max/1024/1*W7z4Cb4CDxMLByCdAramdw.png" /><figcaption>Handling bulk update or create on Django models through filters</figcaption></figure><p>Recently, I came across a case where I needed to handle either bulk creates or bulk updates on a set of Django records within the same endpoint. Unfortunately, Django doesn’t have a way of handling this “either-or” eloquently. I needed to be able to run either operation without the knowledge of primary keys and do so in bulk to minimize the number of statements made against the database.</p><h3>The problem</h3><p>This endpoint had a simple requirement: given a set of objects and a combination of fields to filter by, I needed to create new records if they did not already exist, or update them with the new value if they did.</p><p>Another way to look at this is through an example of the request body:</p><pre>[<br>    {<br>        &quot;category_id&quot;: 23,<br>        &quot;subcategory_id&quot;: 1,<br>        &quot;post_id&quot;: 445,<br>        &quot;value&quot;: &quot;A test value&quot;<br>    },<br>    {...}<br>]</pre><p>If a record already existed in the table with:</p><ul><li>a category_id of 23,</li><li>a subcategory_id of 1,</li><li>a post_id of 445,</li></ul><p>I’d need to update that record’s value field with the value provided in the request. Otherwise, I need to create a new record with this data. If any of those three fields did not match, then it would be considered a separate record (such as the case where subcategory_id=2 ).</p><p>The equivalent expression would look something like this:</p><pre>Demo.objects.filter(category_id=23, subcategory_id=1, post_id=445).exists()</pre><p>The problem statement was straightforward enough, and in normal contexts, should be simple to solve.</p><h3>An important caveat</h3><p>However, there was an issue: due to how this data was being created, no primary keys were being provided in the request, and this endpoint is supposed to handle bulk operations. Identifying if the provided records already existed would have been a single statement, but I couldn’t check what models already existed in bulk (using the <a href="https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.query.QuerySet.in_bulk">in_bulk</a> method) without primary keys.</p><p>Django’s in_bulk method doesn&#39;t provide a way to filter by several field names like we would need in this case. It&#39;s convenient when we have a single list of values, but falls short in more complex cases. Instead, I had to resort to making linear checks through filtering to see if the record existed:</p><pre>records = [<br>    {<br>        &quot;id&quot;: Demo.objects.filter(<br>            category_id=record.get(&quot;category_id&quot;),<br>            subcategory_id=record.get(&quot;subcategory_id&quot;),<br>            post_id=record.get(&quot;post_id&quot;)<br>        )<br>        .first()<br>        .id<br>        if Demo.objects.filter(<br>            category_id=record.get(&quot;category_id&quot;),<br>            subcategory_id=record.get(&quot;subcategory_id&quot;),<br>            post_id=record.get(&quot;post_id&quot;)<br>        ).first()<br>        is not None<br>        else None,<br>        **record,<br>    }<br>    for record in records<br>]</pre><p>This statement looks a bit complex, so let’s break it down. We’re using list comprehension to return a list of dicts, iterating over every object in the request. For each dict, we’re adding a new id key which will hold the primary key of the record that exists given the values, or a value of None if the record can&#39;t be found in the database. We&#39;re using the filter statement from above to make this comparison. We&#39;re then unpacking the data from the request alongside the id key.</p><h3>The solution</h3><p>We now have an id key for every record. Django doesn&#39;t offer a bulk upsert or update_or_create method, so we have to run <a href="https://docs.djangoproject.com/en/4.0/ref/models/querysets/#bulk-create">bulk_create</a> and <a href="https://docs.djangoproject.com/en/4.0/ref/models/querysets/#bulk-update">bulk_update</a> separately. We&#39;ll do this by splitting our new records list into two separate lists which hold the records to update and the records to create.</p><p>This is easy to achieve: for every dict in the records list, if the id field is None, then we append that record to the list for creation. Otherwise, that record is appended to the list for updates.</p><p>We’ll do another list comprehension to achieve this, and we’ll also want to remove the id field for records that need to be created since it holds a value of None.</p><pre>records_to_update = []<br>records_to_create = []</pre><pre>[<br>    records_to_update.append(record)<br>    if record[&quot;id&quot;] is not None<br>    else records_to_create.append(record)<br>    for record in records<br>]</pre><pre>[record.pop(&quot;id&quot;) for record in records_to_create]</pre><p>We have both of the lists that we need now — all that’s left is running our bulk_create and bulk_update methods. By default, Django will attempt to write a single statement for all of the records that you provide it. To limit the length of this statement, we want to specify the batch_size parameter to instruct the method to handle these bulk inserts at a rate of 1000 records per statement.</p><pre>created_records = Demo.objects.bulk_create(<br>    [Demo(**values) for values in records_to_create], batch_size=1000<br>)</pre><pre># Unless you&#39;re using Django 4.0, bulk_update doesn&#39;t return a value<br>Demo.objects.bulk_update(<br>    [<br>        Demo(id=values.get(&quot;id&quot;), value=values.get(&quot;value&quot;))<br>        for values in records_to_update<br>    ],<br>    [&quot;value&quot;],<br>    batch_size=1000<br>)</pre><p>For your bulk_update, Django expects that you specify the list of fields to update as the second argument. Because we are only updating one field in this example, I explicitly set these fields within the model, whereas we are unpacking the full dictionary within the bulk_create statement.</p><p>Here is the full code within a viewset:</p><pre>from rest_framework import generics, status<br>from rest_framework.response import Response<br>from api.models import Demo<br>from api.serializers import DemoSerializer</pre><pre>class DemoViewset(generics.ListCreateAPIView):<br>    def post(self, request):<br>        records = request.data.get(&quot;data&quot;)<br>        <br>        # Let&#39;s define two lists: <br>        # - one to hold the values that we want to insert,<br>        # - and one to hold the new values alongside existing primary keys to update<br>        records_to_create = []<br>        records_to_update = []<br>        <br>        # This is where we check if the records are pre-existing,<br>				# and add primary keys to the objects if they do<br>        records = [<br>            {<br>                &quot;id&quot;: Demo.objects.filter(<br>                    category_id=record.get(&quot;category_id&quot;),<br>                    subcategory_id=record.get(&quot;subcategory_id&quot;),<br>                    post_id=record.get(&quot;post_id&quot;)<br>                )<br>                .first()<br>                .id<br>                if Demo.objects.filter(<br>                    category_id=record.get(&quot;category_id&quot;),<br>                    subcategory_id=record.get(&quot;subcategory_id&quot;),<br>                    post_id=record.get(&quot;post_id&quot;)</pre><pre>                ).first()<br>                is not None<br>                else None,<br>                **record,<br>            }<br>            for record in records<br>        ]<br>        <br>        # This is where we delegate our records to our split lists: <br>        # - if the record already exists in the DB (the &#39;id&#39; primary key), add it to the update list.<br>        # - Otherwise, add it to the create list.<br>        [<br>            records_to_update.append(record)<br>            if record[&quot;id&quot;] is not None<br>            else records_to_create.append(record)<br>            for record in records<br>        ]<br>        <br>        # Remove the &#39;id&#39; field, as these will all hold a value of None,<br>				# since these records do not already exist in the DB<br>        [record.pop(&quot;id&quot;) for record in records_to_create]<br>        <br>        <br>        created_records = Demo.objects.bulk_create(<br>            [Demo(**values) for values in records_to_create], batch_size=1000<br>        )<br>        <br>        # Unless you&#39;re using Django 4.0, bulk_update doesn&#39;t return a value<br>        Demo.objects.bulk_update(<br>            [<br>                Demo(id=values.get(&quot;id&quot;), value=values.get(&quot;value&quot;))<br>                for values in records_to_update<br>            ],<br>            [&quot;value&quot;],<br>            batch_size=1000<br>        )<br>        <br>        # We may want to return different statuses and content based on the type of operations we ended up doing.<br>        message = None<br>        if len(records_to_update) &gt; 0 and len(records_to_create) &gt; 0:<br>            http_status = status.HTTP_200_OK<br>        elif len(records_to_update) &gt; 0 and len(records_to_create) == 0:<br>            http_status = status.HTTP_204_NO_CONTENT<br>        elif len(records_to_update) == 0 and len(records_to_create) &gt; 0:<br>            http_status = status.HTTP_201_CREATED<br>            message = DemoSerializer(created_records, many=True).data<br>            <br>        return Response(message, status=http_status)</pre><h3>Other approaches considered</h3><p>Initially, I felt weary about this solution, as I would be making a SELECT statement against my model&#39;s table for every record to check if it exists by filtering. It felt naive and inefficient. After a bit of reading, however, I found that there wasn&#39;t a good solution for this or at least one that was widely agreed upon.</p><p>As stated previously, Django doesn’t have an eloquent way of handling bulk updates/creates without knowledge of primary keys. You can’t easily run bulk upserts against the database, at least without writing raw SQL, which could be time-consuming and complex. While the SQL approach is <a href="https://www.peterbe.com/plog/simple-or-fancy-upsert-in-postgresql-with-django">faster</a>, you risk writing longer expressions that may be less readable or take too much time if you have a simpler case. I wanted something quick and easy, that I knew would work well enough despite potentially taking a minor performance hit.</p><p>You can also consider the approach of <a href="https://stackoverflow.com/questions/58981173/bulk-upsert-with-django">defining a temporary table</a>, and then copying the newly inserted data to your actual table — but that’s cumbersome and can be more difficult to follow. You have an additional table to maintain in your schema, and it can be harder to trace how data is flowing.</p><p>Lastly, there’s a PyPI package called <a href="https://pypi.org/project/django-bulk-update-or-create/">django-bulk-update-or-create</a>, which adds a Manager to your model’s QuerySet. This requires you to import another package for your project, and has been reported to suffer from similar performance drawbacks (many SELECT statements over a large list of models), and may not be feasible if you only have to perform these operations in one view.</p><h3>The consensus</h3><p>This approach isn’t the most efficient, but it’s enough of a solution. With more reading on how to approach this problem, the consensus was that it would be easiest to split your records into two lists: that of which models exist, and models which would need to be created. You could then run a bulk update and bulk create on each list, respectively. At one point, I asked myself:</p><p>Why can’t I just run a bulk update the same way that I bulk create?</p><p>In other words, I wanted to write Demo.objects.bulk_update(Demo(**values)), where I would unpack the dict into the model and expect Django the intelligently handle conflicts. As it turns out, you can&#39;t do this, as the statement does not know a primary key. Trying to do this results in an exception:</p><p>ValueError: All bulk_update() objects must have a primary key set.</p><p>I couldn’t find a good workaround for this, so splitting these lists and doing filtering again felt like the best option.</p><p>Why do these operations in bulk?</p><p>Using bulk_create and bulk_update is ideal so that we can use a single statement against the database. As I mentioned earlier, Django also allows us to use the batch_size parameter to ensure the statement doesn&#39;t become overly long, which otherwise could lead to too much CPU and memory usage when executing statements. Our goal was to minimize the number of API requests being made between the two services, and reduce the load on the database, so bulk operations were the perfect candidate.</p><p>This can be further optimized by batching the process and running it through jobs; however, I’ll leave it up to you to figure out what strategy you want to employ for better memory management and performance.</p><p><em>Originally published at </em><a href="https://romansorin.com/blog/handling-bulk-update-or-create-on-django-models-through-filters"><em>https://romansorin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1741184dc30" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>