Django orm-tips

3,287 views

Published on

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,287
On SlideShare
0
From Embeds
0
Number of Embeds
1,030
Actions
Shares
0
Downloads
44
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Django orm-tips

  1. 1. Django ORM Tips Tareque Hossain
  2. 2. values_list, only & select_related
  3. 3. Use context <ul><li>Templates have known performance weaknesses </li></ul><ul><li>Know your templates (what data/ variables are in use?) and prepare data in view </li></ul><ul><li>Context is passed between views and templates for a reason </li></ul><ul><li>Minimize queryset evaluations and ORM calls in templates </li></ul><ul><li>Template tags are nice, but will slow you down if you are making ORM calls </li></ul>
  4. 4. Use count() <ul><li>len(QuerySet) is not a good idea </li></ul><ul><li>Evaluating full querysets for boolean values is wasteful </li></ul><ul><li>Don’t retrieve objects if you don’t use them </li></ul><ul><li>Use count and save it if you plan to use it later </li></ul>
  5. 5. Indices <ul><li>Index will not magically solve your problem </li></ul><ul><li>Creating index requires a lot of space and may be expensive </li></ul><ul><li>DB will read ALL index data in addition to reading the table data </li></ul><ul><li>So don’t just go around creating index for each field in your model </li></ul><ul><li>Fields (columns) that will have nearly unique values are better candidates (pk/ unique auto) </li></ul><ul><li>Which fields appear in your filters most? </li></ul>
  6. 6. Order By <ul><li>Looks naïve, but the DB will go crazy trying to sort your data </li></ul><ul><li>Indices help in increasing order_by performance significantly </li></ul><ul><li>Indices may not be used for sorting if you order by multiple fields even if they’re indices </li></ul><ul><li>Indices may not be used for sorting if you mix ascending and descending filters </li></ul>
  7. 7. That’s it! <ul><li>@tarequeh </li></ul><ul><li>@pbs </li></ul><ul><li>codexn.com </li></ul>

×