2015-05-28 04:21:04 +00:00
|
|
|
|
2015-05-28 12:41:38 +00:00
|
|
|
def merge(from_obj, to_obj):
|
2015-05-28 04:21:04 +00:00
|
|
|
for related in from_obj._meta.get_all_related_objects():
|
|
|
|
accessor_name = related.get_accessor_name()
|
|
|
|
varname = related.field.name
|
2015-05-28 19:07:51 +00:00
|
|
|
|
2015-05-28 12:41:38 +00:00
|
|
|
if related.multiple:
|
2015-05-28 19:07:51 +00:00
|
|
|
field = getattr(from_obj, accessor_name)
|
2015-05-28 12:41:38 +00:00
|
|
|
field.all().update(**{varname: to_obj})
|
|
|
|
elif related.one_to_one:
|
|
|
|
try:
|
2015-05-28 19:07:51 +00:00
|
|
|
field = getattr(from_obj, accessor_name)
|
|
|
|
try:
|
|
|
|
getattr(to_obj, accessor_name)
|
|
|
|
except Exception as e:
|
|
|
|
# doesn't exist, safe to overwrite
|
|
|
|
setattr(field, varname, to_obj)
|
|
|
|
field.save()
|
2015-05-28 12:41:38 +00:00
|
|
|
except Exception as e:
|
2015-05-28 19:07:51 +00:00
|
|
|
# from_obj one to one isn't set, skip
|
|
|
|
pass
|
2015-05-28 12:41:38 +00:00
|
|
|
else:
|
|
|
|
import pdb; pdb.set_trace()
|
|
|
|
raise Exception('unknown code path')
|
2015-05-28 04:21:04 +00:00
|
|
|
|
2015-05-28 18:53:05 +00:00
|
|
|
for related in from_obj._meta.get_all_related_many_to_many_objects():
|
2015-05-28 04:21:04 +00:00
|
|
|
accessor_name = related.get_accessor_name()
|
2015-05-28 18:53:05 +00:00
|
|
|
if accessor_name:
|
|
|
|
varname = related.field.name
|
|
|
|
field = getattr(from_obj, accessor_name)
|
|
|
|
if related.many_to_many:
|
|
|
|
for f in field.all():
|
|
|
|
getattr(f, varname).remove(from_obj)
|
|
|
|
getattr(f, varname).add(to_obj)
|