[Fixed]-Django – Query extended models effeciently

1πŸ‘

βœ…

You’re using select_related, which is good. I think you can optimize your query by using a Q, which essentially lets you filter for either type 1 or type 2 in this case.

from django.db.models import Q

BaseModel.objects.filter(Q(type=1) | Q(type=2)).select_related('extendedmodela').select_related('extendedmodelb')

EDIT

You can use the double-underscore notation to access deeper fields that are on related models. eg.

 .select_related('extendedmodela', 'extendedmodela__fkfieldname')
πŸ‘€denvaar

0πŸ‘

Why not just pass a mixed bag to the dropdown. This is no longer a QuerySet, but the dropdown won’t mind:

qs = list(ExtendedModelA.objects.select_related('whatever_fk_needed')) +\
     list(ExtendedModelB.objects.select_related('whatever_fk_needed'))

Whatever instance is selected, will have the same id as its BaseModel instance.

πŸ‘€user2390182

Leave a comment