from django.core.management.base import BaseCommand, CommandError from organiser.models import Organiser from theme.models import Theme, Tag from functions.form_check import translit_with_separator import MySQLdb from MySQLdb.cursors import DictCursor def convert_to_int(st): if not st: return None deduct = ('-','(',')','.',' ') for elem in deduct: st = st.replace(elem, '') if st.isdigit(): return int(st) else: return None class Command(BaseCommand): def handle(self, *args, **options): db = MySQLdb.connect(host="localhost", user="root", passwd="qazedc", db="expomap_ru", charset='utf8', cursorclass=DictCursor) cursor = db.cursor() sql = """SELECT DISTINCT(customers_company) as name, specialize, otrasly as theme, tags, adress, phone, fax, email, website, twitter, about, customers_company.url FROM customers LEFT JOIN customers_company ON customers.customers_company=customers_company.title WHERE customers_status = 4 """ cursor.execute(sql) res = cursor.fetchall() for o in res: if not o.get('name'): continue phone = convert_to_int(o.get('phone')) fax = convert_to_int(o.get('fax')) url = o['url'] if not url: url = translit_with_separator(o.get('name')) if isinstance(o['email'], unicode): organiser = Organiser(url=url, phone=phone, fax=fax, email=o.get('email', ''), twitter=o.get('twitter', '') ) organiser.translate('ru') organiser.name = o.get('name') organiser.specialization = o.get('specialize') organiser.address_inf = o.get('adress') organiser.description = o.get('about') if organiser.name: print('not_saved: %s'%o['name']) organiser.save() print('saved: %s'%str(organiser)) theme = None theme_id = o.get('theme') if theme_id: try: theme = Theme.objects.get(id=theme_id) except Theme.DoesNotExist: continue organiser.theme.add(theme) if not theme: continue tags = o.get('tags') if tags: tags = tags.split(',') if tags: for tag_id in tags: try: tag = Tag.objects.get(id=tag_id) except Tag.DoesNotExist: continue if tag.theme == theme: organiser.tag.add(tag) else: continue else: organiser = Organiser(url=translit_with_separator(o['name'])) organiser.translate('ru') organiser.name = o['name'] if organiser.name: organiser.save() print(organiser) print('success')