Skip to content

Instantly share code, notes, and snippets.

@benzkji
Created October 8, 2017 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benzkji/6f8444fd7958449ac6325f982ebc0ed9 to your computer and use it in GitHub Desktop.
Save benzkji/6f8444fd7958449ac6325f982ebc0ed9 to your computer and use it in GitHub Desktop.
hvad2modeltranslation.py
def migrate_to_modeltranslation(queryset, fields):
"""
to be used in data migrations, for migrating nani/hvad to modeltranslation
:param queryset:
:param fields:
:return:
"""
if not queryset.count():
return "nothing to migrate!"
model_name = queryset[0].__class__
print "----------------------------------------------------"
print "migrating: %s (%s records)" % (model_name, queryset.count())
for object in queryset:
for translation in object.translations.all():
for field in fields:
value = getattr(translation, field, '')
setattr(object, '%s_%s' % (field, translation.language_code), value)
object.save()
print "finished migrating %s (%s records)" % (model_name, queryset.count())
def migrate_to_modeltranslation_raw(db, queryset, fields):
"""
to be used in data migrations, for migrating nani/hvad to modeltranslation
uses raw sql queries
:param queryset:
:param fields:
:return:
"""
if not queryset.count():
return "nothing to migrate!"
model_name = queryset[0].__class__
print "----------------------------------------------------"
print "migrating: %s (%s records)" % (model_name, queryset.count())
for object in queryset:
# print object.text_de
for translation in object.translations.all():
for field in fields:
value = getattr(translation, field, '')
field_name = '%s_%s' % (field, translation.language_code)
# if getattr(translation, field + "_id", None):
if field == "file":
value = getattr(translation, field + "_id", None)
field_name += "_id"
table_name = object._meta.db_table
pk_field = 'id'
if table_name == 'ceco_cecoproductinfoimage':
pk_field = 'cecoimage_ptr_id'
query = 'UPDATE ' + table_name + ' SET ' + field_name + '=%s WHERE ' + pk_field + '=%s'
print query
print object.pk
db.execute(query, [value, object.pk])
# object.save()
print "finished migrating %s (%s records)" % (model_name, queryset.count())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment