Search code examples
djangodjango-adminmanytomanyfield

How to filter a queryset in django model having a ManyToManyField?


I have a "messages" model which has a ManyToManyField for "user". In the admin site I can add a message for multiple users. I am trying to create a view which can filter the messages according to the user_id. Since a new table in the database is created for this ManyToManyField, how can I achieve the same

class Messages(models.Model):
id = models.AutoField(primary_key=True)
message = models.CharField('Message',max_length=1000)
user = models.ManyToManyField('user',blank=True,null=True)
...

I want to do something like:

def sendMessage(userId)
    messageObj = Messages.objets.filter(user_id=userId)

Can anyone help me and tell how I can filter the messages for a specific user? Thanks in advance.


Solution

  • To filter the messages for a specific user, your code looks correct (it just has a typo). It should be something like this:

    queryset = Messages.objects.filter(user=user)
    

    If you want to use the userID (I would rename it to be user_id, personally):

    queryset =  Messages.objects.filter(user.id=user_id)
    

    Both of these will give you a queryset, which is an array like structure.You can continue to filter down if you need a more granular value. For example:

    queryset.filter(message="this is my message").first() # this will now give you a single element