【问题标题】:Django find_each (like RoR)Django find_each(如 RoR)
【发布时间】:2014-10-03 20:02:18
【问题描述】:

有没有办法在 django 中使用find_each

根据 Rails 文档:

此方法仅适用于大批量处理 无法一次全部放入内存的记录数量。如果你 只需要循环少于 1000 条记录,这可能会更好 只是为了使用常规的 find 方法。

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

谢谢。

【问题讨论】:

    标签: python ruby-on-rails django


    【解决方案1】:

    一种可能的解决方案是使用内置的Paginator 类(可以省去很多麻烦)。

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

    尝试类似:

    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
    

    或者,您可以根据需要使用limiting options 来迭代结果。

    【讨论】:

    • 这当然可以解决问题。但这应该针对每个模型进行。在 ruby​​ 中,有一个通用的方法可以实现这一点。
    【解决方案2】:

    您可以使用循环和切片查询集来查询整个表的部分内容。

    如果您使用 Debug = True,请务必在每次循环后刷新查询,因为这可能会导致内存问题(Django 会存储在脚本完成或终止之前运行的所有查询)。

    如果您需要限制查询集的结果,您可以将“.all()”替换为适当的“.filter(conditions)”

    from django import db
    from myapp import MyModel
    
    # Getting the total of records in the table
    total_count = MyModel.objects.all().count()
    chunk_size = 1000 # You can change this to any amount you can keep in memory
    total_checked = 0
    
    while total_checked < total_count:
        # Querying all the objects and slicing only the part you need to work
        # with at the moment (only that part will be loaded into memory)
        query_set = MyModel.objects.all()[total_checked:total_checked + chunk_size]
    
        for item in query_set:
            # Do what you need to do with your results
            pass
    
        total_checked += chunk_size
    
        # Clearing django's query cache to avoid a memory leak
        db.reset_queries()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多