如何对外键对象集的对象进行分组

时间:2015-01-29 15:12:19

标签: python django

试图找出如何构建按组模型对列表模型进行分组的查询,并且List具有FK到组(但不是必需的)。所以我需要“Lists Grouped”,然后是剩下的列表。

传递给模板的结构理想情况如下:

  1. 第1组(对象)

    1. 列表1(对象)

    2. 列表2(对象)

  2. 第2组(对象)

    1. 列表3(对象)

    2. list 4(object)

  3. 列表5(对象)

  4. 列表6(对象)

     class List(Publishable):
         title = models.CharField(max_length=255)
         slug = models.SlugField(verbose_name="Title slug")
         excerpt = models.TextField(blank=True)
         description = models.TextField(blank=True)
         my_order = models.PositiveIntegerField(default=0)
         group = models.ForeignKey(
             'ListGroup', verbose_name="List group", null=True, blank=True)
    
         class Meta(object):
             ordering = ('my_order',)
    
         def __unicode__(self):
             return self.title
    
    
     class ListGroup(Publishable):
         title = models.CharField(max_length=255)
         slug = models.SlugField(verbose_name="Title slug")
         excerpt = models.TextField(null=True, blank=True)
         description = models.TextField(null=True, blank=True)
         my_order = models.PositiveIntegerField(default=0)
    
         class Meta(object):
             ordering = ('my_order',)
    
         def __unicode__(self):
             return self.title
    
    
     class ListsListView(ListView):
    
         model = List
    
         def groups_and_lists(self):
    
             ### Would like to returns something in this structure:
    
             # Group 1 (object)
                 # - list 1 (object)
                 # - list 2 (object)
             # Group 2 (object)
                 # - list 3 (object)
                 # - list 4 (object)
    
             ### Then remaining lists not in a group:
    
             # list 5 (object)
             # list 6 (object)
    
         def get_queryset(self):
             return List.objects.filter(
                 Publishable.Q_PUBLISHED).order_by('my_order')
    

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

return ListGroup.objects \
            .annotate(list_count=Count('lists')) \
            .filter(list_count__gte=1) \
            .order_by('my_order') \
            .prefetch_related('lists')