Home > Net >  Django check if many-to-many relationship exists
Django check if many-to-many relationship exists

Time:02-10

I have a kind of social network in Django where people can send direct messages. Within all of those messages, I have a conversation field to show who the messages are between so that I can group the messages by person when displaying them to the user.

I'm trying to figure out how I can search for if a conversation exists. In the print statements below in the view, I get back:

<QuerySet [<Conversation: Sarah and Stephen>, <Conversation: Sarah and James>]>

<QuerySet [<User: Sarah>, <User: Stephen>]>

<QuerySet [<User: Sarah>, <User: James>]>

In the view below, the sender is 'Sarah' and the receiver is 'James', so I'm trying to figure out how I can search for if a conversation between them already exists (through filter or something) by matching them with the kinds of QuerySet lists above so that if so, I can use that conversation and if not, I can create the conversation. I've tried many things but keep getting stuck. I'm pretty new to many-to-many relationships.

The view

def writemessage(request, id):
    profile = Profile.objects.get(id=id)
    context = {
        'profile': profile,
    }
    conversations = Conversation.objects.all()
    print(conversations)
    for each in conversations:
        print(each.participants.all())
    if request.method == 'POST':
        sender = request.user
        receiver = profile.user
        content = request.POST['content']
        timestamp = datetime.now()
        record = Message(sender=sender, receiver=receiver, content=content, timestamp=timestamp)
        record.save()
        senderprofile = Profile.objects.get(user=sender)
        receiverprofile = Profile.objects.get(user=receiver)
        # below is where the code breaks
        record.conversation.add(senderprofile)
        record.conversation.add(receiverprofile)
        return redirect('messagespage')
    return render(request, 'thecode/writemessage.html', context)

My models

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.CharField(max_length=60)
    country = models.CharField(max_length=60)
    skillstolearn = models.CharField(max_length=200)
    skillstoteach = models.CharField(max_length=200)
    description = models.TextField()

    def __str__(self):
        return self.user.username

class Conversation(models.Model):
    participants = models.ManyToManyField(User)
    
    def __str__(self):
        return str(self.participants.all()[0])   ' and '   str(self.participants.all()[1])

CodePudding user response:

For finding Conversation where the M2M only contains those 2 users, you can use chain filters() and use exists() to check if that Conversation exists between those 2 users:

sarah_user = User.objects.get(username="Sarah")
stephen_user = User.objects.get(username="Stephen")
Conversation.objects.filter(participants=sarah_user).filter(participants=stephen_user).exists()
  • Related