Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#26141 closed New feature (wontfix)

__lt__ for model instances

Reported by: Sven R. Kunze Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: tzanke@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

We need to sort a list of model instances (not a queryset).

After some research, we didn't find a standard way to do this with Django model instances. Would it be possible to implement __lt__ for model instances via the meta class mechanism?

Currently, we write a wrapper where we implemented the following __lt__ method:

def __lt__(self, other):
    for criteria in self.object._meta.ordering:
        field = criteria[1:] if criteria.startswith('-') else criteria
        mine = getattr(self.object, field)
        theirs = getattr(other.object, field)
        if isinstance(mine, unicode):
            mine = locale.strxfrm(mine.encode('utf8'))
            theirs = locale.strxfrm(theirs.encode('utf8'))
        if mine == theirs:
            continue
        if criteria.startswith('-'):
            return mine > theirs
        return mine < theirs
    raise NotImplementedError

Please note, that the implementation is locale-aware.

Change History (2)

comment:1 by Tim Graham, 9 years ago

Resolution: wontfix
Status: newclosed

My initial inclination is that it's better to leave this up to each project to implement as needed, as a sensible default may not be so clear. See #22843 for some related discussion. I guess it's worth raising on the DevelopersMailingList -- if you can get a consensus there on how to proceed with the implementation, then let's reopen this.

As a side note, the implementation above assumes the two objects are the same type, or at least that they both have fields with the name as what's in the first models Meta.ordering.

comment:2 by TZanke, 9 years ago

Cc: tzanke@… added
Note: See TracTickets for help on using tickets.
Back to Top