简体   繁体   中英

Fast filter on related fields in django

I have 2 models in my django project.

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. Table A has around 30 different fields and 10.000+ rows and table B has around 15 and 10.000.000+ rows. 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. After that I need to serialize them in JSON where all ModelB packed in one field as array.

Is it possible to perform this around the 1-3 second? If yes, what is the best approach?

I use 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.

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.

As an aside, there is no need to define id = Autofield fields on your models. Django includes them by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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