[Django]-Django prefetch_related not working

1👍

It is normal, that you are seeing fields from ActsInfoModel only. You can access related models via dot notation, like:

acts = ActsInfoModel.objects.all().prefetch_related("actId", "respProposId1", "respProposId2", "respProposId3", "gvtCompo")
for act in acts:
    print act.respProposId1.respPropos

Related models are already prefetched, so it won’t produce any additional queries. FYI, quote from docs:

Returns a QuerySet that will automatically retrieve, in a single
batch, related objects for each of the specified lookups.

👤alecxe

3👍

You haven’t understood the arguments to prefetch_related. It’s not a list of fields, but a list of models.

(Note that your field naming convention is also very misleading – respProposId1 and actId are not IDs, but actual instances of the models. Django has created an underlying field in each case by appending _id, so the db columns are respProposId1_id and actId_id. You should just call the fields resp_propos1 and resp_propos2 – also note that normal style is lower_case_with_underscore, not capWords.)

Leave a comment