Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output SQL generated by Django Admin

How do you output the SQL that Django's admin is generating to query results for the dhangelist pages? I tried overriding queryset() via:

def queryset(self, *args, **kwargs):
    qs = super(MyAdmin, self).queryset(*args, **kwargs)
    print 'sql:',qs.query
    return qs

but even though I'm browsing /admin/myapp/mymodel/?segment=123&date=2012-1-1, this is showing the query:

sql: SELECT myapp_mymodel.id, myapp_mymodel.segment, myapp_mymodel.start_date
FROM myapp_mymodel ORDER BY myapp_mymodel.start_date ASC

Notice the complete lack of any filters I specified in my URL.

I'm trying to debug a weird problem where if I manually query the table in SQL, I see one result, but Django's admin is showing something completely different. I suspect there's a bug in Django that's causing incorrect SQL to be generated, but I need to see the SQL to confirm that that's the problem.

I'm using Django 1.5.

like image 613
Cerin Avatar asked Jan 21 '26 15:01

Cerin


2 Answers

You can simply set in settings.py this logging configuration to have all SQL queries printed on the console

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG'
        },
    }
}

This is the part responsible for printing

       'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG'
        },
like image 171
glowka Avatar answered Jan 24 '26 06:01

glowka


I use the debug_toolbar: https://pypi.python.org/pypi/django-debug-toolbar

Check it out. It's worth it.

like image 22
aldux Avatar answered Jan 24 '26 06:01

aldux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!