#! /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()