from django.core.management.base import BaseCommand from django.db import connections from establishment.management.commands.add_position import namedtuplefetchall from establishment.models import Employee from django.db.models import Q class Command(BaseCommand): help = 'Add employee from old db to new db.' def employees_sql(self): with connections['legacy'].cursor() as cursor: cursor.execute(''' select t.profile_id, t.name from ( select DISTINCT a.profile_id, trim(CONCAT(p.firstname, ' ', p.lastname, ' ', p.email,'') ) as name from affiliations as a join profiles p on p.id = a.profile_id ) t where t.name is not null ''') return namedtuplefetchall(cursor) def handle(self, *args, **options): objects = [] for e in self.employees_sql(): count = Employee.objects.filter(Q(old_id=e.profile_id) | Q(name=e.name)).count() if count == 0: objects.append(Employee(name=e.name, old_id=e.profile_id)) print(e.name) empls = Employee.objects.bulk_create(objects) self.stdout.write(self.style.WARNING(f'Created employee objects.'))