0

does anyone know anything about q objects and searching many to many fields?

class tags(models.Model):

    name = models.CharField(max_length=20)
    
    def __str__(self):
        return self.name

class Item(models.Model):

    item_id = models.CharField(default = random_string,max_length=5)
    tags = models.ManyToManyField(tags, verbose_name="tags")
    description = models.TextField()
    topic = models.TextField()

I am using django-filters to create a filter / search area, below if filters.py:

class ItemFilter(django_filters.FilterSet):


    multi_name_fields = django_filters.CharFilter(method='filter_by_all_name_fields')



    class Meta:
        model = Item
        fields = ['description','topic','tags']
    
    def filter_by_all_name_fields(self, queryset, name, value):
        
        return queryset.filter(
            Q(description__contains=value) | Q(topic__contains=value)  |  Q(tags__contains=value)

        )

When I render the form field "multi_name_fields" I get an error " Related Field got invalid lookup: contains "

The search form functions perfectly without the manytomany field added in but when I add in the "tags" manytomany field it gives me the above error.

Does anybody have any ideas where I am going wrong or what I am missing?

GTEE
  • 11
  • 5

1 Answers1

2

If you want to query value of many-to-many-field-values, you should clarify the field you want to fetch, as below.

from

Q(tags__contains=value)

to

Q(tags__name__contains=value)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Donghyun Lee
  • 166
  • 3