2023-02-01 12:07:32 +01:00
|
|
|
import random
|
|
|
|
|
|
|
|
|
|
from django.conf import settings
|
2023-03-28 19:26:24 +01:00
|
|
|
from django.db import models
|
2023-02-01 12:07:32 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_random_readonly_database_key_if_present_otherwise_default() -> str:
|
|
|
|
|
"""
|
2023-03-17 11:14:08 +01:00
|
|
|
This function returns a string, representing a key in the `DATABASES` django settings.
|
|
|
|
|
If `settings.READONLY_DATABASES` is set, and non-empty, it randomly chooses one of the read-only databases,
|
2023-02-01 12:07:32 +01:00
|
|
|
otherwise it falls back to "default".
|
|
|
|
|
|
2023-03-17 11:14:08 +01:00
|
|
|
This is primarily intended to be used for django's `QuerySet.using()` function
|
2023-02-01 12:07:32 +01:00
|
|
|
"""
|
|
|
|
|
using_db = "default"
|
|
|
|
|
if hasattr(settings, "READONLY_DATABASES") and len(settings.READONLY_DATABASES) > 0:
|
|
|
|
|
using_db = random.choice(list(settings.READONLY_DATABASES.keys()))
|
|
|
|
|
return using_db
|
2023-03-28 19:26:24 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def NON_POLYMORPHIC_SET_NULL(collector, field, sub_objs, using):
|
|
|
|
|
"""
|
|
|
|
|
django-polymorphic has a bug where it doesn't properly handle the `on_delete` argument:
|
|
|
|
|
https://github.com/django-polymorphic/django-polymorphic/issues/229#issuecomment-398434412.
|
|
|
|
|
This is a workaround that uses the same code as the original `SET_NULL` function, but with the
|
|
|
|
|
`non_polymorphic()` function applied to the `sub_objs` queryset.
|
|
|
|
|
"""
|
|
|
|
|
return models.SET_NULL(collector, field, sub_objs.non_polymorphic(), using)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def NON_POLYMORPHIC_CASCADE(collector, field, sub_objs, using):
|
|
|
|
|
"""
|
|
|
|
|
django-polymorphic has a bug where it doesn't properly handle the `on_delete` argument:
|
|
|
|
|
https://github.com/django-polymorphic/django-polymorphic/issues/229#issuecomment-398434412.
|
|
|
|
|
This is a workaround that uses the same code as the original `CASCADE` function, but with the
|
|
|
|
|
`non_polymorphic()` function applied to the `sub_objs` queryset.
|
|
|
|
|
"""
|
|
|
|
|
return models.CASCADE(collector, field, sub_objs.non_polymorphic(), using)
|