Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Django orm-tips


Published on

  • Be the first to comment

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> </li></ul>