from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError

from emailuser.models import User


class Command(BaseCommand):

    args = ''
    help = "Clones the project's User models to emailuser.User models"

    def handle(self, *args, **options):
        user_model = get_user_model()
        if user_model is User:
            raise CommandError("The project is already configured to use "
                "emailuser's User model, so we don't know what user data to "
                "convert. Please change the project's AUTH_USER_MODEL "
                "setting to the previous value so we can find the user data "
                "to convert.")

        if user_model.objects.filter(email='').exists():
            raise CommandError("You have existing user models with blank "
                "email addresses. Please fill in email values for all users "
                "before converting them to emailusers.")

        num_users = user_model.objects.count()
        num_users_unique_email = user_model.objects.values('email').distinct().count()
        if num_users_unique_email < num_users:
            raise CommandError("You have existing user models with the same "
                "email address. Please update these conflicting users' email "
                "addresses to uniquely identify them before converting them "
                "to emailusers.")

        emailuser_model_fields = [f.name for f in User._meta.concrete_fields]
        user_data = user_model.objects.values(*emailuser_model_fields)
        emailusers = (User(**d) for d in user_data)
        User.objects.all().delete()
        User.objects.bulk_create(emailusers)

        # TODO: swap our ContentType for the original user_model's to preserve generic foreign key references?

        self.stdout.write("Converted {} {}.{} models into emailuser.User models".format(
            len(user_data), user_model.__module__, user_model.__name__))

@@ -138,16 +138,100 @@
 andError
+%0Afrom django.core.management.color import no_style%0Afrom django.db import connections
 %0A%0Afrom e
@@ -815,24 +815,255 @@
 convert.%22)%0A%0A
+        if not user_model.objects.exists():%0A            raise CommandError(%22You have no existing user models to convert. %22%0A                %22Hurrah, you can set AUTH_USER_MODEL and continue without %22%0A                %22converting!%22)%0A%0A
         if u
@@ -2006,16 +2006,16 @@
 elete()%0A
-
         
@@ -2052,16 +2052,673 @@
 users)%0A%0A
+        # We bulk created with the same PKs to keep foreign keys intact, but%0A        # that may have broken PK generation for that table (for example, if%0A        # it's a Postgres database, the table's _id_seq sequence may still%0A        # generate 1 next even though we bulk created a User with pk 1).%0A        # So reset the sequences.%0A        for db_name in connections:%0A            conn = connections%5Bdb_name%5D%0A            sql = conn.ops.sequence_reset_sql(no_style(), %5BUser%5D)%0A            cursor = conn.cursor()%0A            try:%0A                for line in sql:%0A                    cursor.execute(line)%0A            finally:%0A                cursor.close()%0A%0A
         

Reset User table's pk sequence after bulk creating