简体   繁体   English

使用Postgres优化Django queryset查询

[英]Optimize Django queryset query with Postgres

I'm using Django 2.1 and python 3.6 I have a query that contains other queries and seems to take too long to evaluate when there is a lot of data to process. 我正在使用Django 2.1和python 3.6,我有一个包含其他查询的查询,并且在处理大量数据时似乎需要很长时间才能评估。 Basically it reaches the db user timeout (10 seconds) so the query fails, and when I try it without timeout, I get the following error message from DB (postgres)after almost a minute: 基本上它达到了db用户超时(10秒),因此查询失败,并且当我尝试不超时时,将近一分钟后,我从DB(postgres)收到以下错误消息:

ERROR:  canceling statement due to conflict with recovery
DETAIL:  User query might have needed to see row versions that must be removed.

My question is - how can I make the query more efficient? 我的问题是-如何使查询更高效? (all used fields are indexed in DB) (所有使用的字段都在数据库中建立索引)

This is the query: 这是查询:

migration_set__qs = Migration.objects.filter(
        migration_id=migration_id,
        migration_version=migration_version,
        migration_data__generated_id__isnull=False
    ).values_list(
        'object_id',
        flat=True
    )

containers__qs = Container.objects.all().exclude(
            Q(id__in=migration_set__qs) | Q(created_at__gte=turned_on_date)
        )

limited_containers = containers__qs[0:10]
num_containers_processed += limited_containers.count()

The 'count()' triggers the evaluation of the query and there it breaks. “ count()”触发对查询的评估,并在那里中断。

First thing I would attempt, would be to change the migration_set_qs into Subquery : 我要尝试的第一件事是将migration_set_qs更改为Subquery

migration_set__qs = Migration.objects.filter(
    migration_id=migration_id,
    migration_version=migration_version,
    migration_data__generated_id__isnull=False
).values(
    'object_id',
)

containers__qs = Container.objects.all().exclude(
    Q(id__in=Subquery(migration_set__qs)) | Q(created_at__gte=turned_on_date)
)

limited_containers = containers__qs[0:10]
num_containers_processed += limited_containers.count()

Although I am not sure if it will solve all your problems. 虽然我不确定是否能解决您的所有问题。 Please let me know it if made any difference, and if I will have any other ideas I will update this answer as well. 如果有什么不同,请告诉我,如果我有其他想法,我也会更新此答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM