Not using foreign keys directly

When working with foreign keys, accessing the related field will result in a database read. That can be eliminated by using *_id, which is the foreign key value that Django has already cached on the object to make this scenario more efficient.

So in practice, do this


def check_hounds(pk, farm_ids):
    hound = HoundsModel.objects.get(pk=pk)
    if hound.farm_id in farm_ids:
      ...

Instead of this


def check_hounds(pk, farm_ids):
    hound = HoundsModel.objects.get(pk=pk)
    if hound.farm.id in farm_ids:
      ...

Are you affected by this? Audit your codebase in seconds to find out.

Configuring this check

Django Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code indirect-foreign-key in your pyproject.toml file.

Read more about configuring Django Doctor.