======
== ==
======
Note Arsmp!

Til Deferrable Initially Deferred

postgre

Today at work I learn something new, I face some unexpected behaviour when test the CRUD functionality, it’s not bug but it’s clearly how stupid I am.

Let say we have table structure like this:

Parent  
Id  
Name  

Child  
Id  
parent_id  
Name  

So I create two test, number 1 test happy path

-- parent already exist with id = 1
INSERT INTO child (parent_id, name)  
VALUES (1, 'childs');  

Expected no error and pass.

Second I tried to insert not existent parent into child

Read more...

Understanding Django Queries

sql postgre json python django

Django ORM is great, but remember, every Django query we write gets translated into raw SQL.

In this post, I’ll show how Django generates those queries, the cost behind them, and how different ORM methods affect performance, in terms of memory, execution time, and how the query is generated.

This post won’t cover indexing or general SQL optimization techniques, it focuses purely on how Django ORM translates queries into raw SQL.

Read more...

Hosting a Blog on an Old Laptop

blog

Living in a third-world country with a weak currency compared to the US dollar makes hobby projects difficult sometimes. I host several of my applications on AWS Lightsail for 7 dollars, it’s cheap, right? But again, in a third-world country, 7 dollars is kinda “big.” So how do we reduce costs? I was inspired by several friends who self-host their own blogs on a homelab server, so why not try it myself?

Read more...

Mock the Failure

python django test pytest

I’m not a big fan of mocking, especially when working with databases. For me, when we create tests involving a database, we can’t just mock the result because I want to make sure my code actually stores the correct data. I think it is important to verify that the data is stored correctly during testing. Even if we have a nice algorithm in our code, if the stored data is incorrect, it becomes useless.

Read more...

Making Raw SQL Easier to Read with Row Factory

python sqlite postgre

One thing that annoy me when using raw query in Python is how the returned value is not “easy to remember”. Look at this query:

import sqlite3
con = sqlite3.connect("library.sqlite3")
query = "SELECT id, isbn, title FROM books"
con = con.execute(query)
rows = con.fetchall()

To print the returned value I must remember the index of each field:

for r in rows:
	print(f"{r[0]} - {r[1]} - {r[2]}")

# index 0 = id
# index 1 = isbn
# index 2 = title

1 - 1234567890 - Book 1 by Author 1
2 - 2345678901 - Book 1 by Author 1
3 - 3456789012 - Book 1 by Author 1
4 - 4567890123 - Book 1 by Author 2
5 - 5678901234 - Book 1 by Author 2

And if you think it’s only coming from sqlite, you’re wrong. I tried PostgreSQL with psycopg and it has same behavior:

Read more...

Til Postgre Json Jsonb

sql postgre json

Several days ago, I heard a joke:

You don’t need Mongo, PostgreSQL is enough.

So… let’s try it!

Scopes

Before we move forward, let’s set the scope of this test. In my experience, the use cases where I used Mongo are:

  • Store raw information coming from request/response, e.g. webhook, API call, etc.

  • Store personalized config with JSON structure.

So we will try to use these cases using json and jsonb column in PostgreSQL.

Read more...

The Reason I Stay Away From Generic Cbv

python django

When I write code in Django for the first time, I feel mesmerized by class-based views (CBV), especially the generic views. Look at this CBV example using Django REST Framework:

# serializer.py
class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'
        
  # views
  class PostListCreate(ListCreateAPIView):
     serializer_class = PostSerializer
     queryset = Post.objects.all()
     
 class PostEdit(RetrieveUpdateDestroyAPIView):
    serializer_class = PostSerializer
    queryset = Post.objects.all()

With this simple code, I already built full CRUD functionality. This code already supports:

Read more...

Django Update Fields

python django

Usually when working with Django ORM and want to update data, there are two patterns I always use: .save() and .update().

When using .save(), the code becomes like this:

model = Model.objects.get(id=1)
model.field = val
model.save()

This code will act like this:

  • Run clean() on Django model
  • Run the actual query
  • Run related signal(s)

Using .update()

When using .update(), usually it’s to change multiple data. So instead of model instance, we use queryset instance.

Read more...

Embrace Typehint In Python

python django

I tried typehint in python and i didn’t like it, especially when working in legacy code, and then i move to other project, wrote golang code, feels good with the type, want to imitate the type in python and yes i visited again the typehint.

Expectation

Before we move forward, I must set expectation to myself. The default Python is dynamic typing, so it will not smooth like Go. Why? Let’s take a look in this code:

Read more...
1 of 1