简体   繁体   中英

Django Managers - Retrieving objects with non-empty set of related objects

I have two classes, Portfolio, and PortfolioImage.

class PortfolioImage(models.Model):
    portfolio     = models.ForeignKey('Portfolio', related_name='images')
    ...

class Portfolio(models.Model):
    def num_images(self):
        return self.images.count()

I want to write a "non-empty portfolio" manager for Portfolio, so that I can do:

queryset = Portfolio.nonempty.all()

I've tried doing something like this, but I don't think this is even close:

class NonEmptyManager(models.Manager):
    def get_query_set(self):
        return super(NonEmptyManager, self).get_query_set().filter(num_images > 0)

I don't really know where to start, and I'm finding the documentation a bit lacking in this area.

Any ideas? Thanks,

First of all according to documentation you cannot use model methods for lookup with filter / exclude clause. Then also you cannot use python operators ( > in your case) with filter / exclude .

To resolve your task if you are using Django 1.1beta:

from django.db.models import Count

#...

def get_query_set(self):
    return super(NonEmptyManager,self).get_query_set()\
      .annotate(num_images=Count('images'))\
      .filter(num_images__gt=0)

But this solution has some limitations.

Another way for Django >= 1.0:

def get_query_set(self):
    return super(NonEmptyManager,self).get_query_set()\
      .filter(images__isnull=True)

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