[Answer]-Number of SQL queries for a django update

1šŸ‘

  1. TastyPie tends to be liberal in its queries. I remember using a good bit of custom dehydrate() functions to get what I wanted. http://django-tastypie.readthedocs.org/en/latest/resources.html?highlight=hydrate#Resource.dehydrate

  2. TastyPie doesnā€™t like table references ā€” itā€™s too easy to get too much information. Cast a suspicious eyeball on code like user = fields.ForeignKey(UserResource, 'user')

  3. for your own app code, thereā€™s a way to ask the Django QuerySet machinery to translate a query into SQL. This, combined with your Postgres logs, should help determine if the issues are with TastyPie or your app queries.

Code:

#!/usr/bin/env python

'''
logquery.py -- expose database queries (SQL)
'''

import functools, os, sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings.local'
sys.path.append('project/project')

from meetup.models import Meeting

def output(arg):
    print arg
    print


class LoggingObj(object):
    def __init__(self, other):
        self.other = other

    def log_call(self, ofunc, *args, **kwargs):
        res = ofunc(*args, **kwargs)
        print 'CALL:',ofunc.__name__,args,kwargs
        print '=>',res
        return res


    def __getattr__(self, key):
        ofunc = getattr(self.other, key)
        if not callable(ofunc):
            return ofunc
        return functools.partial(self.log_call, ofunc)


qs = Meeting.objects.all()
output( qs.query )


qs = Meeting.objects.all()
qs.query = LoggingObj(qs.query)
output( qs.query.sql_with_params() )

output( list(qs) )

Partial output, with SQL:

SELECT ā€œmeetup_meetingā€.ā€idā€, ā€œmeetup_meetingā€.ā€nameā€,
ā€œmeetup_meetingā€.ā€meet_dateā€ FROM ā€œmeetup_meetingā€

CALL: sql_with_params () {}
=> (uā€™SELECT ā€œmeetup_meetingā€.ā€idā€, ā€œmeetup_meetingā€.ā€nameā€, ā€œmeetup_meetingā€.ā€meet_dateā€ FROM ā€œmeetup_meetingā€ā€˜, ()) (uā€™SELECT
ā€œmeetup_meetingā€.ā€idā€, ā€œmeetup_meetingā€.ā€nameā€,
ā€œmeetup_meetingā€.ā€meet_dateā€ FROM ā€œmeetup_meetingā€ā€˜, ())

šŸ‘¤johntellsall

Leave a comment