考虑以下型号:
class Library(models.Model):
name = models.CharField(max_length=64)
books = models.ManyToManyField(Book)
class Book(models.Model):
name = models.CharField(max_length=64)
tags = models.ManyToManyField(Tag)
class Tag(models.Model):
name = models.CharField(max_length=64)
在图书馆管理员中,我想基于它们的标签添加图书,同时保留添加/删除单个图书的选项。
现有选项:
__str__
进行过滤,是否可以通过tags__name
进行过滤?答案 0 :(得分:0)
我最终使用了Django-fsm小部件,并在apply_filter_val
中覆盖了其views.py
方法。现在,我可以过滤键tag:tag_name
,然后选择所有项目。我还添加了一个选项,以过滤由逗号分隔的多个单词。
def apply_filter_val(self, filter_val, queryset):
if filter_val and 'tag:' in filter_val:
tag_tuple = filter_val.split(':')
_, name = tag_tuple
params = {'tags__name': name}
new_base = queryset.filter(**params)
elif filter_val and ',' in filter_val:
new_base = queryset.filter(id__in=filter_val.split(','))
elif filter_val:
q = [Q(**{f'{field}__icontains': filter_val}) for field in self.fields]
if filter_val and q:
new_base = queryset.filter(reduce(self.default_operator, q))
else:
# Return everything if no filter_val or fields are specified.
# This allows for a very straightforward async request, but will
# probably not behave as expected if no fields are specified.
new_base = queryset
if self.obj_limit:
new_base = new_base[:self.obj_limit]
return new_base