Django管理员根据标签来选择m2m个项目(项目的m2m字段)

时间:2019-04-29 13:40:41

标签: django django-admin filtering admin m2m

考虑以下型号:

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)

图书馆管理员中,我想基于它们的标签添加图书,同时保留添加/删除单个图书的选项。

现有选项:

  1. Filter_horizo​​ntal -通过__str__进行过滤,是否可以通过tags__name进行过滤?
  2. Raw_id_fields -与为 Book 指定的任何过滤器一起使用,但您只能选择1个项目。有没有办法允许选择更多的项目? (表格中的复选框)

1 个答案:

答案 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