Created
June 25, 2013 13:16
-
-
Save EmilStenstrom/5858351 to your computer and use it in GitHub Desktop.
Management command to delete users that no longer have a reference to them (Except UserProfile and SocialData in our case).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django.core.management.base import BaseCommand | |
from django.contrib.auth.models import User | |
from emailuser.models import UserProfile | |
from socialdata.models import SocialData | |
class Command(BaseCommand): | |
def _has_relations(self, related_objects, user, whitelist=(User, UserProfile, SocialData)): | |
for related in related_objects: | |
model = related.model | |
has_subobjs = model._base_manager.filter(**{related.field.name: user}).exists() | |
if model not in whitelist and has_subobjs: | |
return True | |
return False | |
def handle(self, *args, **options): | |
all_users = User.objects.filter(is_staff=False) | |
print "%s users to process..." % all_users.count() | |
for i, user in enumerate(all_users.iterator()): | |
if i % 1000 == 0 and i != 0: | |
print "%s users processed..." % i | |
has_relations = self._has_relations(user._meta.get_all_related_objects(), user) | |
if not has_relations: | |
has_relations = self._has_relations(user._meta.get_all_related_many_to_many_objects(), user) | |
if not has_relations: | |
print "Deleting user: ", user | |
user.delete() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment