[Django]-Django Queryset: filtering by related item manager

4๐Ÿ‘

โœ…

As per what I know, there is no way to achieve it using single queryset, since you want to use the active() available within your manager. But you may achieve the result by adding the related name to Page in Block model as:

class Block(models.Model):
    page = models.ForeignKey(Page, related_name='related_block')
    ...

Now your code should be:

active_blocks = Block.objects.active()  # Queryset with all active blocks
# Queryset of Pages with Block in 'active_blocks' 
active_pages = Page.objects.filter(related_block__in=active_blocks)

Now on this QuerySet, you may perform annonate or whatever you desire which is allowed on Pageโ€˜s QuerySet.

0๐Ÿ‘

Why not just add a boolean field on the model, something like is_active, and update it on save() or set_active()? Then youโ€™ll be able to query your Model by that field.

๐Ÿ‘คAndrey Shipilov

Leave a comment