Reputation:
I'm creating a project using Django and I'm wondering how I can make objects distinct. Now I am creating message box part and what I want to do is show up user names who the user have been contacting. My current way is like this
models.py
class Message(models.Model):
''''''
text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='myself')
someone = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='someone')
views.py
def inbox(request):
'''See messages history'''
messages = Message.objects.filter(user=request.user).distinct('someone')
notification = Message.objects.filter(someone=request.user).distinct('user')
return render(request, 'campus_feed/inbox.html', {'messages': messages})
So what I want to do is list the users who is contacting me or I contacted and I don't want to show up the same name multiple times but I cannot come up with good way to filter them. Anyone who can give me tips?
Upvotes: 0
Views: 205
Reputation: 599610
If you want users, you should request users.
User.objects.filter(Q(myself__someone=request.user) | Q(someone__user=request.user))
This gives you all users who are either the "someone" in a message from the current user, or the "user" in a message to the current user. Since you are querying users directly, the is no possibility of duplicates.
Upvotes: 3