qrys Flashcards
1
Q
Django queries cheat sheet
A
To preload foreign key objects into a queryset, use
ModelName.objects.select_related(“field_name”)
To preload reverse foreign key objects into a queryset, use
ModelName.objects.prefetch_related(“modelname_set”)
To preload many to many fields into a queryset, use
ModelName.objects.prefetch_related(“field_name”)
To trigger a query to run, you can use
bool(queryset)
list(queryset)
len(queryset)
To see a field was added using prefetch, use
queryset._prefetched_objects_cache
Note: returns error if theres no prefetched fields
To see the cached field an instance, use
model_instance._state.fields_cache