I may have a classic problem, but I didn't find any snippet allowing me to do it.
I want to sort this model by its fullname.
class ProductType(models.Model):
parent = models.ForeignKey('self', related_name='child_set')
name = models.CharField(max_length=128)
def get_fullname(self):
if self.parent is None:
return self.name
return u'%s - %s' % (unicode(self.parent), self.name)
fullname = property(get_fullname)
I tried sorting by "parent", got infinite loop error. "parent__id" did not sort well.
I could not understand how to use annotate() for concatenating string fields.
I added a custom manager with sorted(), but it returns a list object and prevents my forms.ModelChoiceField to work.
Here's the sort
def all(self):
return sorted(super(ProductTypeManager, self), key=lambda o: o.fullname)
What else is there in the djangonic jungle ? Thanks for your help.