I’m new to Django, and try to develop my resume online.
Here it is my two models :
#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) )
As you can see in my view, I don’t know how to sort only the children (experience) by the field “end_date” in the query.
I tried this:
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' )
But it returns me too many parents…
Would like to know how can I solve it ?
Thank you
You can use Django’s aggregations for this to get the max end_date and then sort on it. For example: