# -*- coding: utf-8 -*- import MySQLdb from MySQLdb.cursors import DictCursor from django.core.management.base import BaseCommand from exposition.models import Exposition from theme.models import Theme class Command(BaseCommand): def handle(self, *args, **options): expos = Exposition.objects.filter(theme__isnull=True, old_url__isnull=False) db = MySQLdb.connect(host="localhost", user="expomap", passwd="7FbLtAGjse", db="old_db", charset='utf8', cursorclass=DictCursor) cursor = db.cursor() find_old_id = """ SELECT products.products_id from products LEFT JOIN `products_description` ON products.products_id=products_description.products_id WHERE url='%s' """ find_themes = "SELECT categories_id FROM `products_to_categories` WHERE `products_id` =%d" for expo in expos: cursor.execute(find_old_id%expo.old_url) old_ids = [item['products_id'] for item in cursor.fetchall()] print expo.old_url for id in old_ids: cursor.execute(find_themes%id) themes_ids = [item['categories_id'] for item in cursor.fetchall()] print themes_ids #if not themes_ids: # continue theme_qs = Theme.objects.filter(id__in=themes_ids) #expo.theme.add(*theme_qs) break print('----------------------')