from django.core.management.base import BaseCommand, CommandError from company.models import Company from theme.models import Theme, Tag from accounts.models import User from functions.form_check import translit_with_separator import datetime 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 * from customers_company" cursor.execute(sql) res = cursor.fetchall() for c in res: phone = convert_to_int(c.get('phone')) fax = convert_to_int(c.get('fax')) url = c['url'] if not url: url = translit_with_separator(c.get('title')) company = Company(id=c['company_id'], url=url, phone=phone, fax=fax, email=c.get('email'), web_page=c.get('website'), twitter=c.get('twitter', '')) company.translate('ru') company.name = c.get('title') company.specialization = c.get('specialize') company.description = c.get('about') company.address_inf = c.get('adress') user = User.objects.safe_get(id=user_id) company.creator = user print('not_saved: %s'%c['title']) company.save() user_id = c['customers_id'] print('saved: %s'%str(company)) if user: user.company = company if not user.last_login: now = datetime.datetime.now() user.last_login = now user.save() theme = None theme_id = c.get('otrasly') if theme_id: try: theme = Theme.objects.get(id=theme_id) except Theme.DoesNotExist: continue company.theme.add(theme) if not theme: continue tags = c.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: company.tag.add(tag) else: continue #print(str(type(res[0]['phone']))) print('success')