[Django]-How do I write an update join postgres query as queryset in Django 1.9?

0👍

Considering you have models and their foreign key relations:

 from django.db.models import Count

 shelves = WhShelf.objects.all()     

 for shelf in shelves:
      count = WhPackage.objects.filter(shelf_id=shelf.id).aggregate(Count('shelf'))
      shelf.update(package_count=count[shelf__count'])

Alterantively, you can run a single query:

WhShelf.objects.annotate(package_count=WhPackage.objects.
                filter(shelf_id=shelf.id).aggregate(Count('shelf'))['shelf__count'])

Leave a comment