7

Click here to load reader

Django orm-tips

Embed Size (px)

Citation preview

Page 1: Django orm-tips

Django ORM Tips

Tareque Hossain

Page 2: Django orm-tips

values_list, only & select_related

Page 3: Django orm-tips

Use context

• Templates have known performance weaknesses• Know your templates (what data/ variables are in

use?) and prepare data in view• Context is passed between views and templates

for a reason• Minimize queryset evaluations and ORM calls in

templates• Template tags are nice, but will slow you down if

you are making ORM calls

Page 4: Django orm-tips

Use count()

• len(QuerySet) is not a good idea• Evaluating full querysets for boolean values is

wasteful• Don’t retrieve objects if you don’t use them• Use count and save it if you plan to use it later

Page 5: Django orm-tips

Indices

• Index will not magically solve your problem• Creating index requires a lot of space and may be

expensive• DB will read ALL index data in addition to reading

the table data• So don’t just go around creating index for each

field in your model• Fields (columns) that will have nearly unique

values are better candidates (pk/ unique auto)• Which fields appear in your filters most?

Page 6: Django orm-tips

Order By

• Looks naïve, but the DB will go crazy trying to sort your data

• Indices help in increasing order_by performance significantly

• Indices may not be used for sorting if you order by multiple fields even if they’re indices

• Indices may not be used for sorting if you mix ascending and descending filters

Page 7: Django orm-tips

That’s it!

• @tarequeh • @pbs• codexn.com