Today I learned: Replace function in Django’s ORM.
Sometimes we stumble across a bug or a change in the business logic that forces us to change the value of a column based on another from the same table. I thought that Django might have this solved and indeed it has through the database functions.
In my case I had to update the value of a column replacing its current value and, at the same time, using the value of another column. This was possible with little code using the function Replace.
An example:
from app.models import File
from django.db.models.functions import Replace
from django.db.models import Value
base_url = "https://random.s3.eu-central-1.amazonaws.com"
File.objects.update(
s3_url=Replace('s3_file_path', Value("s3://random"), Value(base_url))
)
It means that all s3_url
will get the value of s3_file_path
with base_url
instead of "s3://random"
.
Many other interesting functions that usually are solved by pure Python code are available to be run on the database side, such as reverse and many others.
Hope that was useful to you. See ya!
Translations
comments powered by Disqus