【问题标题】:Retrieve all the parent with the children with sorting the children通过对子项进行排序来检索所有父项和子项
【发布时间】:2012-06-22 17:04:00
【问题描述】:

我是 Django 新手,尝试在线开发我的简历。

这是我的两个模型:

#MODELS
class Category( models.Model ):
    help_text = 'Category respresents a category of experience, or school experiments'
    # Name
    name = models.CharField( max_length=500, blank=False )
    # ...

    def __unicode__( self ):
        return self.name


class Experience( models.Model ):
    help_text = 'An experience can be a skill, a school experiment etc.'
    # ordering = ['-end_date']
    parent_category = models.ForeignKey( Category )
    # Name
    # ...
    end_date = models.DateField( 'date of end', blank=True, null=True )
    # ...

    def __unicode__(self):
        return self.name

#View
# index view
def index( request ):
        # Would like something to just order the children
    all_categories = Category.objects.filter().order_by( ???? )
    return render_to_response( 'CMSCV/index.html',
            { 'categories' : all_categories },
            context_instance=RequestContext(request) )

正如您在我看来,我不知道如何按查询中的字段“end_date”仅对子项(经验)进行排序。

我试过了:

Category.objects.all().order_by( 'experience__end_date' ).distinct()

Category.objects.all().order_by( 'experience__end_date' ).distinct('experience__end_date')

Category.objects.all().order_by( 'experience__end_date' ).distinct( 'name' )

但它让我有太多的父母......

想知道如何解决?

谢谢

【问题讨论】:

    标签: django django-models django-queryset


    【解决方案1】:

    您可以使用 Django 的 aggregations 来获取最大 end_date,然后对其进行排序。例如:

    from django.db.models import Max
    Category.objects.all().annotate(max_date=Max('experiences_set__end_date')).order_by('max_date')
    

    【讨论】:

    • 它不起作用,实际上它只是放置了体验的最大日期,并按此最大日期排序。但我只想对孩子进行排序。我不想对类别进行排序,而只想对孩子进行排序。谢谢
    • 哦,您要按顺序打印体验吗?在这种情况下,您将遍历类别,然后执行 category.experiences_set.all().order_by('end_date')
    • 就是这样!非常感谢!
    • 没问题。如果您想接受我的回答,请在左侧勾选“接受”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2011-03-18
    • 2021-11-22
    • 1970-01-01
    • 2011-11-10
    • 2020-09-07
    相关资源
    最近更新 更多