add add_current_model and get_field_value to utils.py
This commit is contained in:
parent
7c5ad70781
commit
ba3a912b6a
2 changed files with 32 additions and 5 deletions
|
@ -11,7 +11,7 @@ from django.utils.translation import ugettext_lazy as _
|
|||
from django.utils.translation import ungettext_lazy
|
||||
|
||||
from c3nav.editor.models.change import Change
|
||||
from c3nav.editor.utils import is_created_pk
|
||||
from c3nav.editor.utils import get_current_obj, get_field_value, is_created_pk
|
||||
from c3nav.editor.wrappers import ModelInstanceWrapper, ModelWrapper
|
||||
from c3nav.mapdata.models import LocationSlug
|
||||
from c3nav.mapdata.models.locations import LocationRedirect
|
||||
|
@ -381,10 +381,8 @@ class ChangeSet(models.Model):
|
|||
model = type(obj)
|
||||
field = model._meta.get_field('titles' if name.startswith('title_') else name)
|
||||
with transaction.atomic():
|
||||
if is_created_pk(obj.pk):
|
||||
current_obj = model()
|
||||
else:
|
||||
current_obj = model.objects.only(field.name).get(pk=obj.pk)
|
||||
current_obj = get_current_obj(model, obj.pk)
|
||||
current_value = get_field_value(current_obj, field)
|
||||
try:
|
||||
current_value = getattr(current_obj, field.attname)
|
||||
except AttributeError:
|
||||
|
|
|
@ -1,2 +1,31 @@
|
|||
from typing import Union
|
||||
|
||||
from django.db import models
|
||||
|
||||
|
||||
def is_created_pk(pk):
|
||||
return isinstance(pk, str) and pk.startswith('c') and pk[1:].isnumeric()
|
||||
|
||||
|
||||
def get_current_obj(model, pk, only_field=None):
|
||||
if is_created_pk(pk):
|
||||
return model()
|
||||
if only_field is not None:
|
||||
return model.objects.only(only_field).get(pk=pk)
|
||||
return model.objects.get(pk=pk)
|
||||
|
||||
|
||||
def get_field_value(obj, field: Union[str, models.Field]):
|
||||
if isinstance(field, str):
|
||||
name = field
|
||||
model = type(obj)
|
||||
field = model._meta.get_field('titles' if name.startswith('title_') else name)
|
||||
else:
|
||||
name = field.name
|
||||
try:
|
||||
current_value = getattr(obj, field.attname)
|
||||
except AttributeError:
|
||||
current_value = field.to_prep_value(getattr(obj, field.name))
|
||||
if name.startswith('title_'):
|
||||
current_value = current_value.get(name[6:], '')
|
||||
return current_value
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue