Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django find_each (like RoR)

Is there way to use find_each in django?

According to the rails documentation:

This method is only intended to use for batch processing of large amounts of records that wouldn’t fit in memory all at once. If you just need to loop over less than 1000 records, it’s probably better just to use the regular find methods.

http://apidock.com/rails/ActiveRecord/Batches/ClassMethods/find_each

Thanks.

like image 411
Danilo Aburto Vivians Avatar asked Oct 16 '25 16:10

Danilo Aburto Vivians


1 Answers

One possible solution could be to use the built-in Paginator class (could save a lot of hassle).

https://docs.djangoproject.com/en/dev/topics/pagination/

Try something like:

from django.core.paginator import Paginator
from yourapp.models import YourModel

result_query = YourModel.objects.filter(<your find conditions>)

paginator = Paginator(result_query, 1000) # the desired batch size

for page in range(1, paginator.num_pages + 1):
   for row in paginator.page(page).object_list:
       # here you can add your required code

Or, you could use the limiting options as per needs to iterate over the results.

like image 191
Abhishek Agarwala Avatar answered Oct 18 '25 05:10

Abhishek Agarwala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!