【问题标题】:django-mptt : Filter all categories having an online entrydjango-mptt :过滤所有具有在线条目的类别
【发布时间】:2012-03-09 11:23:45
【问题描述】:

我将这个 Django Blog App 类别系统传递给 django-mptt。

我遇到的问题与_get_online_category 方法有关。 此方法允许我仅获取具有Entry 的类别。

def _get_online_categories(self):
    """
    Returns categories with entries "online" inside.
    Access this through the property ``online_entry_set``.
    """
    from models import Entry
    return Category.objects.filter(entries__status=Entry.STATUS_ONLINE).distinct()

我怎样才能修改它,这样我也将拥有具有条目的类别的类别?

例如:

我有Spain > Malaga,而马拉加用前一种方法得到了Entry,我只会得到Malaga,但不会得到Spain,我想两者都有。

第二个问题:

如何从父类别中获取所有条目?

例如从西班牙获得马拉加的帖子?

def _get_online_entries(self):
    """
    Returns entries in this category with status of "online".
    Access this through the property ``online_entry_set``.
    """
    from models import Entry        
    return self.entries.filter(status=Entry.STATUS_ONLINE)

online_entries = property(_get_online_entries)

这将返回西班牙的空结果。

【问题讨论】:

    标签: django django-queryset django-mptt mptt


    【解决方案1】:

    This 看起来是第一种方式的好解决方案:

    def _get_online_categories(self):
        """
        Returns categories with entries "online" inside.
        Access this through the property ``online_entry_set``.
        """
        from models import Entry
        queryset =  self.categories.filter(entries__status=Entry.STATUS_ONLINE)
    
        new_queryset = queryset.none() | queryset
        for obj in queryset:
            new_queryset = new_queryset | obj.get_ancestors()
        return new_queryset
    

    第二个问题

    这样的事情会成功:

    def _get_online_entries(self):
        """
        Returns entries in this category with status of "online".
        Access this through the property ``online_entry_set``.
        """
        from models import Entry        
        return Entry.objects.filter(status=Entry.STATUS_ONLINE, 
                                    category__lft__gte=self.lft, 
                                    category__rght__lte=self.rght)
    
    online_entries = property(_get_online_entries)
    

    【讨论】:

      猜你喜欢
      • 2016-10-11
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      相关资源
      最近更新 更多