Home > Net >  I have a huge but not complex sql query that must convert to django orm query
I have a huge but not complex sql query that must convert to django orm query

Time:10-23

I have to convert the following sql query but i don't know how to convert it to equal query in django orm I would be very happy if you can :)))

select dialog_messages.*, 
    sender.first_name as sender_first_name,
     sender.last_name as sender_last_name,
     sender.cell_number as sender_cell_number,
     sender.avatar_full_path as sender_avatar_full_path, receiver.first_name as receiver_first_name,
     receiver.first_name as receiver_first_name,
     receiver.last_name as receiver_last_name,
     receiver.cell_number as receiver_cell_number, receiver.avatar_full_path as receiver_avatar_full_path from dialog_messages`` inner join user sender on ``sender``.``user_id`` = dialog_messages``.``sender_id`` inner join user receiver on receiver``.``user_id`` = ``dialog_messages``.``receiver_id`` where `dialog_id`` = ? order by ``dialog_messages``.``id`` desc

CodePudding user response:

You should use select_related (and also look at prefetch_related). You can check the reference at:

In your code, without knowing more about your models I think you could start with something like:

DialogMessage.objects.select_related('sender', 'receiver')
  • Related