检索包含子项的子项的所有父项

时间:2012-06-22 17:04:01

标签: django django-models django-queryset

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

但它给了我太多的父母......

想知道我该如何解决?

谢谢

1 个答案:

答案 0 :(得分:0)

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

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