From ba3a912b6a63e5bb74e1be80735d3090ed4f8a2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laura=20Kl=C3=BCnder?= Date: Sun, 25 Jun 2017 12:17:22 +0200 Subject: [PATCH] add add_current_model and get_field_value to utils.py --- src/c3nav/editor/models/changeset.py | 8 +++----- src/c3nav/editor/utils.py | 29 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/c3nav/editor/models/changeset.py b/src/c3nav/editor/models/changeset.py index 14ad04af..5697127c 100644 --- a/src/c3nav/editor/models/changeset.py +++ b/src/c3nav/editor/models/changeset.py @@ -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: diff --git a/src/c3nav/editor/utils.py b/src/c3nav/editor/utils.py index 515099a6..fd7bc58b 100644 --- a/src/c3nav/editor/utils.py +++ b/src/c3nav/editor/utils.py @@ -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