Django: how to query parent model based on a filter of a child model?

北战南征 提交于 2021-01-28 07:10:18

问题


I have those classes (simplified for sake of clarity):

class Entity(models.Model):
    adresses = models.ManyToManyField(Address,
                                      related_name='persons',
                                      through='EntityAddress')

class EntityAddress(models.Model):
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE,
                               blank=False, null=False)
    address_type = models.ForeignKey(AddressType, models.CASCADE,
                                     blank=False, null=False)
    address = models.ForeignKey(Address, on_delete=models.CASCADE,
                                blank=False, null=False)

class Address(models.Model):
    summary = models.CharField(max_length=250, blank=True, null=True)
    way = PolygonField(default=None, blank=True, null=True)

class Person(Entity):
    user = models.OneToOneField(User, blank=False, null=False,
                                on_delete=models.CASCADE)

I want to have all Person's whose addresses have a "not null" way.

I do it like this:

for p in Person.objects.all():
    for e_a in EntityAddress.objects.filter(entity=p,
                                            address__way__isnull=False,):
        # do whatever here:
        pass

This is way too slow! Is there a way to make only one request?


回答1:


You could do it maybe with a nested in query?

Something like:

not_null_ea = Entity.objects.filter(addresses__way__isnull=False).values('addresses')
for p in Person.objects.filter(
        addresses__in=not_null_ea).prefetch_related('entityaddress_set):
    for a_e in p.entityaddress_set:
        pass

This way at least you would not be looping through Person objects yourself which really is quite slow.




回答2:


I don't have a django project with concrete (multi-table) model inheritance at hand so I can't double-check it works, but theoretically this should do what you want:

Person.objects.filter(adresses__way__isnull=False)

This might help by the way...



来源:https://stackoverflow.com/questions/57784766/django-how-to-query-parent-model-based-on-a-filter-of-a-child-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!