<commit_before>---
layout: post
title: 'django note'
date: 2017-01-05
author: Pengfei.X
version: 0.1
categories: [devnotes, ]
---


## What's the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you're
going to be selecting is a single object, so OneToOneField or a ForeignKey.

You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields
as you stated or reverse ForeignKeys. Just to clarify what I mean by "reverse ForeignKeys" here's an example:

    class ModelA(models.Model):
        pass

    class ModelB(models.Model):
        a = ForeignKey(ModelA)
<commit_msg>update django devnote add log all sql queries<commit_after>---
layout: post
title: 'django note'
date: 2017-01-05
author: Pengfei.X
version: 0.1
categories: [devnotes, ]
---

## log all sql queries

    LOGGING = {
        'version': 1,
        'filters': {
            'require_debug_true': {
                '()': 'django.utils.log.RequireDebugTrue',
            }
        },
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'filters': ['require_debug_true'],
                'class': 'logging.StreamHandler',
            }
        },
        'loggers': {
            'django.db.backends': {
                'level': 'DEBUG',
                'handlers': ['console'],
            }
        }
    }

[log all sql queries](http://stackoverflow.com/questions/4375784/log-all-sql-queries)


## What's the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you're
going to be selecting is a single object, so OneToOneField or a ForeignKey.

You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields
as you stated or reverse ForeignKeys. Just to clarify what I mean by "reverse ForeignKeys" here's an example:

    class ModelA(models.Model):
        pass

    class ModelB(models.Model):
        a = ForeignKey(ModelA)

{'fraction_non_alphanumeric': 0.09857142857142857, 'fraction_numerical': 0.013333333333333334, 'mean_word_length': 2.6286701208981, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '515621', 'n_tokens_mistral': 635, 'n_tokens_neox': 588, 'n_words': 213}