2011-02-16 143 views
0

我有一个项目和类别模型。只有返回多个结果才能返回django视图

我期待只为类别返回的结果,如果他们有1个项目或更多...

这是我迄今为止,但它似乎返回错误的结果。

def category(): 
    return { 'categories': Category.objects.filter(project=True).all().order_by('id')} 

有什么想法吗?

class Category(models.Model): 
    title = models.CharField(max_length=30) 
    slug = models.SlugField(max_length=100, blank=True, null=True) 

class Project(ImageModel): 
    ... 
    ... 
    location = models.CharField(max_length=50, help_text='The city, town or area of the project.', null=True, blank=True) 
    categories = models.ManyToManyField(Category) 
    ... 
    ... 
+0

硬盘的文档,看看发生了什么事情也没有看到模型。 – 2011-02-16 12:23:51

回答

1

Category.project是一个管理器。

您可以使用注释。喜欢的东西:

Category.objects.annotate(projects=Count('project')).filter(projects__gt=1) 

查看annotations and aggregations