Database cleanup

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#! /usr/bin/env python
'''Cleans database from garbage: objects which lost their required relations.'''

import setup_environment

from django.db import connection
from django.db.models.fields.related import RelatedField

from django.core.exceptions import ObjectDoesNotExist

def main(argv=None):
    tables = connection.introspection.table_names()
    seen_models = connection.introspection.installed_models(tables)
    for model in seen_models:
        cleanup_model(model)
        
def cleanup_model(model):
    print 'Cleaning ' + str(model) + '...'
    
    #get relational fields:
    fields = []
    for f in model._meta.fields:
        if isinstance(f, RelatedField):
            fields.append(f)
    
    for obj in model.objects.all():
        for f in fields:
            try:
                getattr(obj, f.name)
            except ObjectDoesNotExist:
                print 'Object #%i has unrelated field: %s == %s' % \
                    (obj.pk, f.name, f.value_from_object(obj))
                if f.null == False: 
                    print ' * Removing this object...'
                    obj.delete()
                    break
                else:
                    print ' * Fixing object with null value...'
                    setattr(obj, f.name, None)
            
            
if __name__ == '__main__':
    main()

More like this

  1. Remove old fields on dumpdata generated json by facundo_olano 1 year, 7 months ago
  2. Use class name in templates by polarbear 5 years, 11 months ago
  3. Read more link by nny777 4 years, 10 months ago
  4. dumpdata/loaddata with MySQL and ForeignKeys by cmgreen 5 years, 4 months ago
  5. Database migration and dump/load script by akaihola 6 years, 1 month ago

Comments

(Forgotten your password?)