Django custom order_by

前端 未结 3 2032
余生分开走
余生分开走 2020-12-09 22:37

I\'ve got a model eg. Car with a foreign key eg. Owner, which may or may not be blank. The Car has a creation_date.

I would like to order these cars by date, but if

3条回答
  •  长情又很酷
    2020-12-09 23:08

    Have a look at this similar question: Good ways to sort a queryset? - Django

    You can't use the model's Meta ordering as it only accepts one field

    https://docs.djangoproject.com/en/dev/ref/models/options/#ordering

    You can't use the query order_by('creation_date', 'birthdate') as it only sorts by birthdate if they have the same creation_date

    So, you could write a custom manager to do incorporate a custom sort for you.

    import operator
    class CarManager(models.Manager):
        def get_query_set(self):
            auths = super(CarManager, self).get_query_set().all().order_by('-creation')
            ordered = sorted(auths, key=operator.attrgetter('birthday'))
            return ordered
    
    class Car(models.Model):
        sorted = CarManager()
    

    so now you can query:

    Car.sorted.all()
    

    to get all a queryset of sorted car's

提交回复
热议问题