tags:

views:

55

answers:

1
+1  Q: 

Django Group By

Hello. I'm writing a simple private messenger using Django and am implementing message threading.

Each series of messages and replies will have a unique thread_id that will allow me to string sets of messages together. However, in the inbox view ALL of the messages are showing up, I'd just like to group by the thread_id so that although a thread could have 20 messages, it only shows up once in the inbox.

It'd be a pretty simple

SELECT msg_id, msg_text, subject, from_user_id, to_user_id, date_time, is_read,
thread_id WHERE to_user_id='foo' GROUP BY thread_id FROM inbox_message;

however, I can't seem to execute it using django's ORM

any thoughts?

+1  A: 

What do you want to achieve with this SQL statement?

It will work on some DBMS (ie. MySQL), but it isn't legal. When your are using GROUP BY statement, you can select only columns your are grouping by, and aggregates (SUM, AVG, COUNT etc.). Other columns are forbidden, because DBMS don't know what data return (ie. should it return subject of first message, second one or what?).

If you wan't some sumup about thread, other than count of messages, probably best solution for you is to add new columns to thread table (BTW. do you have thread table?).

Tomasz Wysocki
Ah, I see. Yes this query works on MySQL which is why I thought of it as being valid. Basically all I'm doing is listing messages, so all I care about is the subject line of any of the messages, since it will remain the same on replies. No thread table..I'm just adding a thread_id to related messages (e.g. replies to a parent message) and am stringing messages together based on whether or not they have the same thread_id. Is there any way to accomplish what I'm trying to do without adding some sort of parent/child flag or a thread table? In theory I should be able to group by thread_id, right?
john m.
yes the problem is in my data model. thanks for the help
john m.
If you are sure that your subject is exactly the same, you can add it to GROUP BY: `GROUP BY thread_id, subject`. If you have subject in GROUP BY, you can use it in SELECT too. But this solution is bad, because you have data redundancy. There are two good solutions: 1. add Thread model, and move subject there. 2. Add reply_to column (then you can search for first messages in thread using `reply_to is NULL` and delete `thread_id` column.
Tomasz Wysocki