Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

python - Django custom order_by

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 the car has an owner, the date of birth of the owner must be taken instead of the creation_date of the car.

Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...