Skip to content

JSON field increment with F expressions #357

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion requirements/local.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ boto3-stubs==1.26.81

flake8==6.0.0
isort==5.12.0
black==23.1.0
black==23.3.0
pre-commit==3.2.2
Empty file.
31 changes: 31 additions & 0 deletions styleguide_example/blog_examples/f_expressions/db_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from django.db.models import CharField, F, IntegerField, JSONField, Value
from django.db.models.expressions import Func
from django.db.models.functions import Cast


class JSONIncrement(Func):
"""
This is an example from this blog post
- https://www.hacksoft.io/blog/django-jsonfield-incrementation-with-f-expressions
Django docs reference
- https://docs.djangoproject.com/en/4.2/ref/models/expressions/#f-expressions
"""

function = "jsonb_set"

def __init__(self, full_path, value=1, **extra):
field_name, *key_path_parts = full_path.split("__")

if not field_name:
raise ValueError("`full_path` can not be blank.")

if len(key_path_parts) < 1:
raise ValueError("`full_path` must contain at least one key.")

key_path = ",".join(key_path_parts)

new_value_expr = Cast(Cast(F(full_path), IntegerField()) + value, CharField())

expressions = [F(field_name), Value(f"{{{key_path}}}"), Cast(new_value_expr, JSONField())]

super().__init__(*expressions, output_field=JSONField(), **extra)
16 changes: 16 additions & 0 deletions styleguide_example/blog_examples/f_expressions/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.db import models


class SomeDataModel(models.Model):
"""
This is an example from this blog post
- https://www.hacksoft.io/blog/django-jsonfield-incrementation-with-f-expressions
"""

name = models.CharField(
max_length=255,
blank=True,
)
stored_field = models.JSONField(
blank=True,
)
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from django.test import TestCase

from styleguide_example.blog_examples.f_expressions.db_functions import JSONIncrement
from styleguide_example.blog_examples.models import SomeDataModel


class JSONIncrementTests(TestCase):
def setUp(self) -> None:
self.first_entity_stored_field = {"first_key": 1, "second_key": 2, "third_key": 3}
self.second_entity_stored_field = {"first_key": 4, "second_key": 5, "third_key": 6}
self.increment_value = 10

def test_json_increment_in_model(self):
SomeDataModel.objects.bulk_create(
[
SomeDataModel(name="First name", stored_field=self.first_entity_stored_field),
SomeDataModel(name="Second name", stored_field=self.second_entity_stored_field),
]
)

first_entity = SomeDataModel.objects.first()
second_entity = SomeDataModel.objects.last()

expected_first_entity_stored_field = self.first_entity_stored_field
actual_first_entity_stored_field = first_entity.stored_field

expected_second_entity_stored_field = self.second_entity_stored_field
actual_second_entity_stored_field = second_entity.stored_field

self.assertEqual(expected_first_entity_stored_field, actual_first_entity_stored_field)
self.assertEqual(expected_second_entity_stored_field, actual_second_entity_stored_field)

SomeDataModel.objects.filter(name="First name").update(
stored_field=JSONIncrement("stored_field__first_key", self.increment_value)
)

first_entity = SomeDataModel.objects.first()
second_entity = SomeDataModel.objects.last()

"""
Expect only first_entity JSON field with name first_key to be incremented
"""

expected_first_entity_stored_field = {
"first_key": self.first_entity_stored_field["first_key"] + self.increment_value,
"second_key": self.first_entity_stored_field["second_key"],
"third_key": self.first_entity_stored_field["third_key"],
}
actual_first_entity_stored_field = first_entity.stored_field

expected_second_entity_stored_field = self.second_entity_stored_field
actual_second_entity_stored_field = second_entity.stored_field

self.assertEqual(expected_first_entity_stored_field, actual_first_entity_stored_field)
self.assertEqual(expected_second_entity_stored_field, actual_second_entity_stored_field)
21 changes: 21 additions & 0 deletions styleguide_example/blog_examples/migrations/0002_somedatamodel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Generated by Django 4.1.6 on 2023-05-10 06:34

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('blog_examples', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='SomeDataModel',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, max_length=255)),
('stored_field', models.JSONField(blank=True)),
],
),
]
2 changes: 2 additions & 0 deletions styleguide_example/blog_examples/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from django.db import models
from django.utils import timezone

from .f_expressions.models import SomeDataModel # noqa


class TimestampsWithAuto(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
Expand Down