from django.core.management.base import BaseCommand from theme.models import Tag, Theme import MySQLdb from MySQLdb.cursors import DictCursor class Command(BaseCommand): def handle(self, *args, **options): db = MySQLdb.connect(host="localhost", user="expomap", passwd="7FbLtAGjse", db="old_db", charset='utf8', cursorclass=DictCursor) cursor = db.cursor() # id 3732 duplicate tag with bad name(2 spaces) sql_tag = "SELECT id, title, url FROM tags WHERE id != 3732" sql_theme = "SELECT categories_id as id, url FROM categories_description;" cursor.execute(sql_theme) res = cursor.fetchall() """ # themes for item in res: id = item['id'] old_url = item['url'] theme = Theme.objects.get(id=id) theme.old_url = old_url theme.save() print(theme) """ # tags cursor.execute(sql_tag) res = cursor.fetchall() updated_tags = [] for item in res: id = item['id'] old_url = item['url'] title = item['title'] #print(id) print(title.encode('utf8')) try: tag = Tag.objects.get(id=id, translations__name=title, translations__language_code='ru') tag.old_url = old_url updated_tags.append(id) tag.save() except Tag.DoesNotExist: Tag.objects.exclude(id__in=updated_tags).filter(translations__name=title).update(old_url=old_url) print(len(updated_tags))