Obvious Django tip: one query is better than two

To often, I see unnecessary queries in Django code: first get a complete data object, just so it can be used in another query.

For example, we have an employee_id and want to get the Company of the Employee (both data models, where employee is the ForeignKey field of Company).

So, don't do this:
# get Employee object
try:
    employee = Employee.objects.get(id = employee_id)
except ObjectDoesNotExist:

    pass
# get Company object
try:
    company = Company.objects.get(employee = employee)
except ObjectDoesNotExist:

    pass

But instead, make a single query, directly using the ForeignKey:
# get Company object
try:
    company = Company.objects.get(employee__id = employee_id)
except ObjectDoesNotExist:

    pass

See https://docs.djangoproject.com/en/dev/topics/db/queries/ for more info

Comments

Popular posts from this blog

Handling control characters (escaping) in python for json and mysql

python port sniffer with pcapy and impacket

Django field, form and model validation process