Django custom order_by

前端 未结 3 2031
余生分开走
余生分开走 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:30

    This is possible by falling back to SQL:

    Car.objects.filter(...).extra(select={'odate': '''
      if(owner_id,
         (select date_of_birth from owner_table where id=owner_id),
         creation_date
      )
    '''}).order_by('odate')
    

    if function is MySQL-specific. In case of SQLite or Postgres you should use case statement.

提交回复
热议问题