【发布时间】:2020-12-15 15:14:43
【问题描述】:
我需要使用多对多类别字段过滤文档的 API 响应。这是我的模型:
class Document(models.Model):
name = models.CharField(max_length = 100, blank = True)
file = models.FileField(null = True, upload_to='documents/', validators=[FileExtensionValidator(allowed_extensions=['pdf'])])
date_created = models.DateTimeField(auto_now_add = True, null = True)
category = models.ManyToManyField(Category)
company = models.ForeignKey(Company, null = True, on_delete = models.SET_NULL)
author = models.ForeignKey(Employee, null = True, on_delete = models.SET_NULL)
这个模型的序列化器是:
class DocumentSerializer(serializers.ModelSerializer):
class Meta:
model = Document
fields = "__all__"
我正在尝试用这个过滤它:
class DocumentFilter(filters.FilterSet):
# having_category = filters.Filter(name = 'category', lookup_type = 'in')
class Meta:
model = Document
fields = {
'company': ['exact'],
'author': ['exact'],
# 'category': ['in']
}
我尝试使用this 解决方案,正如您在代码中看到的那样,但没有成功。 与公司和作者一起过滤正在工作,我只遇到了类别问题。
我应该如何创建过滤器?
【问题讨论】:
标签: django filter django-rest-framework