0

我是 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' )

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

想知道我该如何解决?

谢谢

4

1 回答 1

0

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

from django.db.models import Max
Category.objects.all().annotate(max_date=Max('experiences_set__end_date')).order_by('max_date')
于 2012-06-22T17:11:14.240 回答