python - Django QuerySet order_by string evaluation -


i'm trying sort queryset based on how objects in queryset evaluated strings.

so model looks this:

class system(models.model):   operating_system = models.charfield(...)   language = models.charfield(...)   locale = models.charfield(...)    def __unicode__(self):     def __clean(orig, new):       if orig none or orig == "":         if new none or new == "":           return ""         else:           return str(new)       else:         if new none or new == "":           return str(orig)         else:           return str(orig) + " " + str(new)     name = none     attr in system._meta.fields:       if attr.name != "id":         name = __clean(name, getattr(self, attr.name))     m2mfield in system._meta.many_to_many:       object in getattr(self, m2mfield.name).all():         name = __clean(name, object)        if name == "":       return "undefined"     return name 

and, i'd able make query like:

system.objects.filter(...).order_by('__unicode__') 

i'm wondering if there's way without custom manager.

thanks!

in __unicode__ end single string represents system object. instead of calculating every time need it, calculate once , save onto model.

class system(models.model):     operating_system = models.charfield(...)     language = models.charfield(...)     locale= models.charfield(...)     name = models.charfield(editable=false, ...)      def save(self, *args, **kwargs):         self.name = self._calculate_name()         super(system, self).save(*args, **kwargs)      def __unicode__(self):         return self.name      def _calculate_name(self):         # string manipulation , relationship stuff 

now can order name easily

system.objects.filter(...).order_by('name') 

there caveats approach, depends on usage of system. also, not worry space, that's opinion!


expanding on caveats

since field 'denormalized', suffers same problems other relational data isn't normalized face. denormalization can introduce update anomalies (a field or relation name depends on can change without change name if change happens through other route system model's save() method. can slow down writes (in case small amount), can increase space requirements (again not problem here in opinion), , whole wack of other stuff google love tell i'm sure.

i think have careful updating .name whenever should be, consider under conditions 'cleaning' code produce different results. if, example, had os table can change description of os without touching system table, have realize .name not updated save os, require recalculation. there mechanisms signals , overriding more save() methods. batch update them necessary.

it depends heavily on use case, not illustrated here. full of people narrow down best solution if present use case more completely.


Comments