Answer the question
In order to leave comments, you need to log in
How to get the latest message?
Hello.
It is necessary to receive and serialize the last message between users.
I am using django/django rest framework.
Model:
class Message(models.Model):
"""
Model for user messages.
- Who
- Whom
- When
- Message
- Status
"""
user_sender = models.ForeignKey(User, related_name="sender")
user_receiver = models.ForeignKey(User, related_name="receiver")
send_date = models.DateTimeField(auto_now_add=True)
message = models.CharField(max_length=500)
status = models.BooleanField(default=False)
def __unicode__(self):
return u'%s %s ->%s' % (self.send_date, self.user_sender, self.user_receiver)
users1 = Message.objects.filter(Q(user_sender_id=token.user_id) |
Q(user_receiver_id=token.user_id))\
.values('user_sender_id')
users2 = Message.objects.filter(Q(user_sender_id=token.user_id) |
Q(user_receiver_id=token.user_id))\
.values('user_receiver_id')
users = User.objects.filter(Q(id__in=users1) |
Q(id__in=users2))
serializer = MessagePreviewSerializer(users, context={'user_id': token.user_id}, many=True)
class MessagePreviewSerializer(serializers.ModelSerializer):
info = UserProfileSerializer(many=True, read_only=True)
last_message = serializers.SerializerMethodField('message_preview')
def message_preview(self, obj):
user_id = self.context.get("user_id")
message = get_object_or_404(Message, Q(user_sender_id=user_id, user_receiver_id=obj.id) |
Q(user_receiver_id=user_id, user_sender_id=obj.id))
return message.message
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name', 'email', 'info', 'last_message')
Answer the question
In order to leave comments, you need to log in
https://docs.djangoproject.com/en/1.8/ref/models/q...
user_send_last_msgs = Message.objects.\
filter(user_sender=token.user_id).\
order_by('-send_date', 'user_receiver').\
distinct('user_receiver')
# distinct('user_receiver') postgres only
user_receive_last_msgs = Message.objects.\
filter(user_receiver=token.user_id).\
order_by('-send_date', 'user_sender').\
distinct('user_sender')
for message in last_msgs:
print message.user_sender
print message.user_receiver
print message.send_date
print message.message
print message.status
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question