Improve default behavior for clone operation

copy all fields but uuid, and show flash message(s)
This commit is contained in:
Lance Edgar 2019-10-17 16:17:43 -05:00
parent 85e67a974a
commit 65bcd8da2a

View file

@ -36,7 +36,8 @@ import sqlalchemy as sa
from sqlalchemy import orm from sqlalchemy import orm
import sqlalchemy_continuum as continuum import sqlalchemy_continuum as continuum
from sqlalchemy_utils.functions import get_primary_keys from sqlalchemy_utils.functions import get_primary_keys, get_columns
from rattail.db import model, Session as RattailSession from rattail.db import model, Session as RattailSession
from rattail.db.continuum import model_transaction_query from rattail.db.continuum import model_transaction_query
@ -1110,6 +1111,9 @@ class MasterView(View):
self.configure_clone_form(form) self.configure_clone_form(form)
if self.request.method == 'POST' and self.request.POST.get('clone') == 'clone': if self.request.method == 'POST' and self.request.POST.get('clone') == 'clone':
cloned = self.clone_instance(instance) cloned = self.clone_instance(instance)
self.request.session.flash("{} has been cloned: {}".format(
self.get_model_title(), self.get_instance_title(instance)))
self.request.session.flash("(NOTE, you are now viewing the clone!)")
return self.redirect(self.get_action_url('view', cloned)) return self.redirect(self.get_action_url('view', cloned))
return self.render_to_response('clone', { return self.render_to_response('clone', {
'instance': instance, 'instance': instance,
@ -1122,7 +1126,21 @@ class MasterView(View):
pass pass
def clone_instance(self, instance): def clone_instance(self, instance):
raise NotImplementedError """
This method should create and return a *new* instance, which has been
"cloned" from the given instance. Default behavior assumes a typical
SQLAlchemy record instance, and the new one has all "column" values
copied *except* for the ``'uuid'`` column.
"""
cloned = self.model_class()
for column in get_columns(instance):
if column.name != 'uuid':
setattr(cloned, column.name, getattr(instance, column.name))
self.Session.add(cloned)
self.Session.flush()
return cloned
def touch(self): def touch(self):
""" """