Django Managers - 检索具有非空相关对象集的对象

[英]Django Managers - Retrieving objects with non-empty set of related objects


I have two classes, Portfolio, and PortfolioImage.

我有两个类,Portfolio和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:

我想为Portfolio编写一个“非空投资组合”经理,这样我就能做到:

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,

有任何想法吗?谢谢,

1 个解决方案

#1


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.

首先根据文档,您不能使用模型方法来使用filter / exclude子句进行查找。那么你也不能使用带有过滤/排除的python运算符(在你的情况下为>)。

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

要在使用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:

Django> = 1.0的另一种方式:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2009/05/01/910c702707f82a8d75b15bc48e16762c.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告