Parsa
Parsa

Reputation: 151

how to make a message model in Django where you can choose more than one person as the recipient

So, I'm trying to make a messaging model(between users) in Django admin where the sender can choose more than one recipient for the message. Models.py:

class Message(models.Model):
    subject = models.CharField(_("title"), max_length=50, blank=True)
    body = models.TextField(verbose_name=")
    sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE,editable=False)
    recipient = models.ManyToManyField(settings.AUTH_USER_MODEL) 
    def __str__(self):
        return str(self.subject)

admin.py:

class MessageAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change): 
        instance = form.save(commit=False)
        instance.sender = request.user
        instance.save()
        form.save_m2m()
        return instance

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        sender_query = qs.filter(sender=request.user)
        recipient_query = qs.filter(recipient=request.user)
        return sender_query | recipient_query

My current approach is the code above using a ManyToManyField. But this has created two bugs:

  1. The sender will see the same message more than once if more than one recipient are chosen, for example if the sender chooses three recipients, he will have three of the same message in his queryset

  2. The sender will not be able to open the message he has sent(if more than one recipient are chosen) because this error will get raised:get() returned more than one Message -- it returned 2!. of course the "2" can be any other number

The thing I can't figure out Is that these bugs won't produce if the sender is superuser(And I assume that means there is a problem with my get_queryset code)

What am I doing wrong in here?

Upvotes: 0

Views: 560

Answers (1)

Oussama Tachi
Oussama Tachi

Reputation: 154

  • You just need to add related_name in each field, the related_name must be different or you can use related_name='+'

  • from django documentation the related_name is the name to use for the relation from the related object back to this one. It’s also the default value for related_query_name

  • in your case you set the same name for different relations

Upvotes: 1

Related Questions