'How to filter queryset with mutiple m2m values?
I'm tryna filter Seo model here. I want to get objects that has the brand dependency and the model dependency. Code
class SeoListView(generics.ListAPIView):
serializer_class = SeoListSerializer
def get_queryset(self) -> QuerySet:
queryset = Seo.objects.all()
dependencies = self.request.query_params.get('dependencies')
if dependencies is not None:
dependencies = [str(dep).strip() for dep in dependencies.split(',')]
print(dependencies)
# for dep in dependencies:
# query.add(Q(dependencies__dependency__exact=dep), Q.AND)
query = reduce(lambda q, dep: q & Q(dependencies__dependency__exact=dep), dependencies, Q())
queryset = queryset.filter(query)
return queryset
class Dependency(models.Model):
dependency = models.SlugField(
'Зависимость', unique=True,
help_text='Перечислите зависимости через нижнее подчеркивание. Пример: brand_model'
)
def __str__(self) -> str:
return f'Зависимость {self.dependency}'
class Meta:
verbose_name = 'Зависимость'
verbose_name_plural = 'Зависимости'
class Seo(models.Model):
statuses = (
(1, 'Дефолтная'),
(2, 'Дополнительная')
)
_delimiter = SEOService().delimiter
_help_text = (
f'Если вы ввели Купить {_delimiter}, а зависимость - car,'
f' то после сохранения получится Купить car машину. '
f'Все {_delimiter} заменяются на соотв. им зависимости.'
)
dependencies = models.ManyToManyField(
Dependency,
verbose_name='Зависимости',
blank=True,
help_text='Оставьте пустым, если это дефолтный шаблон.'
)
h1 = models.CharField(
'Заголовок(h1)', max_length=200,
help_text=_help_text
)
title = models.CharField(
'Заголовок(title)', max_length=200,
help_text=_help_text
)
description = models.CharField(
'Описание', max_length=200,
help_text=_help_text
)
keywords = models.TextField(
'Ключевые слова',
help_text=_help_text
)
status = models.IntegerField('Статус', choices=statuses, blank=True, help_text='Не трогать руками', null=True)
def __str__(self) -> str:
return f'Настройка сео'
class Meta:
verbose_name = 'Настройка'
verbose_name_plural = 'Настройки'
I am SURE i've got the objects which have both model and brand dependency in the db. For some reason it's just not working, fun thing tho, when i try to filter it OR that magically works.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
