mirror of
https://framagit.org/la-chariotte/la-chariotte.git
synced 2025-05-01 11:22:24 +02:00
56 lines
2 KiB
Python
56 lines
2 KiB
Python
# Generated by Django 4.2.1 on 2023-08-08 09:20
|
|
|
|
from django.db import migrations, models
|
|
import base36
|
|
import random
|
|
|
|
|
|
def create_code_from_pk(pk):
|
|
"""When a grouped order is created, we compute a unique code that will be used in url path
|
|
How we generate this code :
|
|
1. The instance pk, written in base36 (max 5 digits for now - we assume that there will not be more than 60466175 grouped orders)
|
|
2. A random int written in base36 (5 digits long)
|
|
3. Only the 6 first digits of this string
|
|
The use of pk in the beginning of the string guarantees the uniqueness, and the random part makes that we cannot guess the url path.
|
|
"""
|
|
base_36_pk = base36.dumps(pk)
|
|
random_string = base36.dumps(
|
|
random.randint(1727605, 60466175)
|
|
) # generates a 5 digits long string
|
|
return f"{base_36_pk}{random_string}"
|
|
|
|
|
|
def set_code_default(apps, schema_editor):
|
|
"""Provides a default code to existing grouped orders during migration"""
|
|
GroupedOrder = apps.get_model("order", "GroupedOrder")
|
|
for grouped_order in GroupedOrder.objects.all().iterator():
|
|
grouped_order.code = create_code_from_pk(grouped_order.pk)
|
|
grouped_order.save()
|
|
|
|
|
|
def reverse_set_code_default(apps, schema_editor):
|
|
"""Reverse the set_code default function"""
|
|
GroupedOrder = apps.get_model("order", "GroupedOrder")
|
|
for grouped_order in GroupedOrder.objects.all().iterator():
|
|
grouped_order.code = ""
|
|
grouped_order.save()
|
|
|
|
|
|
class Migration(migrations.Migration):
|
|
dependencies = [
|
|
("order", "0024_alter_item_options"),
|
|
]
|
|
|
|
operations = [
|
|
migrations.AddField(
|
|
model_name="groupedorder",
|
|
name="code",
|
|
field=models.CharField(auto_created=True, null=True),
|
|
),
|
|
migrations.RunPython(set_code_default, reverse_set_code_default),
|
|
migrations.AlterField(
|
|
model_name="groupedorder",
|
|
name="code",
|
|
field=models.CharField(auto_created=True),
|
|
),
|
|
]
|