简体   繁体   English

快速过滤django中的相关字段

[英]Fast filter on related fields in django

I have 2 models in my django project. 我的django项目中有2个模型。

ModelA(models.Model):
    id = models.AutoField(primary_key=True)
    field1 = ...
    ~
    fieldN = ...

ModelB(models.Model):
    id = models.AutoField(primary_key=True)

    a = models.ForeignKey(A, on_delete=models.CASCADE)

    field1 = ...
    ~
    fieldN = ...

Here I have one-to-mane relation A->B. 在这里,我有一对一的关系A-> B. Table A has around 30 different fields and 10.000+ rows and table B has around 15 and 10.000.000+ rows. 表A有大约30个不同的字段和10.000+行,表B有大约15和10.000.000+行。 I need to filter firstly by the several ModelA fields and then for each of the filtered ModelA row/object get related ModelB objects and filter them by several fields. 我需要首先通过几个ModelA字段进行过滤,然后为每个过滤的ModelA行/对象获取相关的ModelB对象,并按几个字段过滤它们。 After that I need to serialize them in JSON where all ModelB packed in one field as array. 之后我需要在JSON中序列化它们,其中所有ModelB在一个字段中打包为数组。

Is it possible to perform this around the 1-3 second? 是否有可能在1-3秒左右执行此操作? If yes, what is the best approach? 如果是,最好的方法是什么?

I use PostgreSQL. 我使用PostgreSQL。

EDIT: 编辑:

Now I am doing it like chain .filter() on simple ModelA fields and then iterate over resulted QuerySet and get set of ModelB for each ModelA instance,but i suspect, that the second part of this solution will slow down whole process, so I suppose there is a better way to do it. 现在,我在简单的ModelA字段上执行链接.filter() ,然后遍历结果QuerySet并为每个ModelA实例获取ModelB集,但我怀疑,此解决方案的第二部分将减慢整个过程,所以我假设有更好的方法来做到这一点。

It may be faster to do a query like this: 执行这样的查询可能会更快:

model_a_queryset = ModelA.objects.filter(field=whatever)
model_b_queryset = ModelB.objects.filter(a__in=model_a_queryset)

Because Django does lazy queryset evaulation, this will only result in one hit to the database. 因为Django执行了懒惰的查询集评估,所以这只会导致数据库的一次命中。

As an aside, there is no need to define id = Autofield fields on your models. 另外,您无需在模型上定义id = Autofield字段。 Django includes them by default. Django默认包含它们。

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

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