How do I remove duplicate users in django?

I need to remove duplicate users in django (by double I mean two or more users with the same email).

If, for example, there are three entries:

id    email
3     c@c.com
56    c@c.com
90    c@c.com

      

I need to delete records 56 and 90 and keep the oldest record ID -> 3

Is there a way to quickly do this.

Thanks:)

+2


a source to share


3 answers


The answer to RZ is actually almost correct. I don't know if this is the best, but it works. Therefore, for this sole purpose, you can use it.

However, I would like to add and fix some things.

from django.contrib.auth.models import User

def delete_duplicate_users():
  // first find all email addresses (with kind of a 'group by')
  emails = User.objects.values('email').distinct()

  for e in emails:
    users = User.objects.filter(email=e['email']).order_by('date_joined')[1:]
    for u in users:
      u.delete()

      

I tried this with a small example and it worked. But I highly recommend that you check it out before using it on your production system!



Hope it helps.

// Edit

I would also recommend that you don't add users if the email is already registered. There must be a built-in method to achieve this. And if only you could not subclass Djangos user model with your own user model and override the save method.

+2


a source


users = User.objects.filter(email='c@c.com').order_by('join_date')[1:]
for u in users:
    u.delete()

      



I forget that Query Query supports slicing as above and can't test right now. If not, you just need to extract the first item and remove the rest.

+1


a source


You can get email addresses like this.

from django.contrib.auth.models import User
from django.db.models import Count

duplicate_emails = [i['email'] for i in User.objects.values('email').annotate(
    Count('email')).filter(email__count__gt=1)]

      

You can then view the email addresses and decide what to do with them. This example removes the user with the old date last_login.

for email in duplicate_emails:
    user = User.objects.filter(email=email).order_by('last_login')[0]
    user.delete()

      

0


a source







All Articles