Search code examples
django-modelsmany-to-manylookupdjango-related-manager

How to use 'contains' with manytomany field?


I have a model:

class Tasks(models.Model):
    name = models.CharField(max_length = 50, null = True, blank = True)
    assigned_to = models.ManyToManyField(User, null = True, blank = True)


I have to execute a query

tasks_for_myuser = Tasks.objects.filter(assigend_to__contains = myuser)

But this is throwing an error. django.core.exceptions.FieldError: Related Field got invalid lookup: contains

Please help!


Solution

  • If you are trying to filter Tasks which has assigned_to field set to myuser, you can simply query like this. tasks_for_myuser = Tasks.objects.filter(assigend_to = myuser) You don't really require contains here, since it is a many-to-many field.