django distinct doesn't return just unique fields -
i've models chat messages 3 fields:
sender, recipient ( foreignkey user model ) , message textfield.
i'm trying select unique conversations either sender either recipient field (exclude request.user). , i'm bit messed in how implement that.
i've 2 issues:
message.objects.filter(q(sender = request.user)|q(recipient = request.user)).values('sender').distinct()
doesn't return list of unique records ( order_by ). i've lot absolutely same senders: {'sender': 4l}, {'sender': 4l}
(the same recipients).
and second issue is:
do need concatenate 2 queysets (for senders , recipients) or there way whole list of conversations current request.user?
upd. ok, here table content:
mysql> select id, sender_id, recipient_id, body messages_message ; +----+-----------+--------------+-----------+ | id | sender_id | recipient_id | body | +----+-----------+--------------+-----------+ | 1 | 4 | 1 | message 1 | | 2 | 4 | 1 | message 2 | +----+-----------+--------------+-----------+
and here result of
message.objects.filter(q(sender = request.user)|q(recipient = request.user)).values('sender').distinct() [{'sender': 4l}, {'sender': 4l}]
but expected [{'sender': 4l}]
.
so, what's wrong?
upd2. model:
class message(models.model): body = models.textfield(_("body")) sender = models.foreignkey(user, related_name='sent_messages', verbose_name=_("sender")) recipient = models.foreignkey(user, related_name='received_messages', null=true, blank=true, verbose_name=_("recipient")) sent_at = models.datetimefield(_("sent at"), null=true, blank=true)
i need select conversation partners (people sent or received message request.user) of current user.
just $.02, think sort of logic handled better python sql. if use query params specific 1 db, kind of defeats purpose of orm, in opinion.
i try this:
messages = message.objects.filter(q(sender = request.user)|q(recipient = request.user)) ## need 'q'? ##
then:
partners = set() m in messages: partners.add(m.sender) partners.add(m.recipient)
if going @ set often, cache it.
but might better make partners
field of user
, , add every time message sent. no complex query ever need made, simple user.partners
.
i assume need user
object send message anyway, shouldn't overhead.
Comments
Post a Comment