Django defer() and only() queryset not working?

Viewed 724

Please guide me if i misunderstand the correct use of defer() or only() in queryset.

This is the code where i am trying to get only seleted fields data from Donor model to make process fast because it has 2000 entries and when i use all() it takes time to fetch data.

def donor(request):
        # donors = Donors.objects.all()
        donors = Donors.objects.only('donorid','donor_type','title','donor_name','address',
                                       'mobile_no','jamatkhana')
        # donors = Donors.objects.defer('donorid','donor_type','title','donor_name','address',
                                       'mobile_no','jamatkhana')
        return render(request,"hod_template/add_donor_template.html",{"donors":donors})

After use of "only()" or "defer()" the result is still same as "all()" none of the selected field neither deferred nor only. even it takes more time to load than all().

Please tell me how to get only these selected field data from donor model. i also tell you i tried "Values()" Method as well but the problem is the "jamatkhana" field is ForeignKey and i want its data as well. but using of "Values()" method it only get values not foreignkey inner data. hope i explain properly?

1 Answers

but the problem is the jamatkhana field is ForeignKey and I want its data as well.

Likely fetching the related object that is referred to by the ForeignKey is the bottleneck. You can use .select_related(…) [Django-doc] to make a JOIN at the database side and thus fetch the data of the related jamatkhana field with the same query. Without .select_related(…), it will make an extra query per Donor to fetch the related data, and thus this easily results in a lot of extra queries to the database.

You thus can render this with:

donors = Donors.objects.select_related('jamatkhana')

As @AbdulAzizBarkat however points out, typically pagination is used to reduce the amount of data from the webserver to the client, and often by slicing a queryset, you also reduce the bandwidth (and sometimes the number of queries) from the database to the Django/Python layer.

Related