问题描述
我正在尝试使用 django-tables2 和 django-filters 使用反向多对多关系创建过滤器。我可以获得多对多对象的过滤器,但我想对相关表中的一个字段进行过滤。我怎么能做到这一点?
示例:
models.py
class Author(models.Model):
articles = models.ManyToManyField(Article,blank=True)
age = models.IntegerField()
hometown = models.ForeignKey(Town,on_delete=models.CASCADE,null=True,blank=True)
@property
def articles(self):
return ','.join(art.title for art in self.articles.all())
class Article(models.Model):
title = models.CharField(max_length=255,blank=True)
publication_date = models.DateField()
published = models.BooleanField(default=False)
tables.py
class AuthorTable(tables.Table):
articles = tables.columns.Column(accessor='articles')
class Meta:
model = Author
attrs = {
'class': 'table table-responsive table-striped','thead' : {
'class': 'thead-dark'
}
}
过滤器.py
class AuthorFilter(django_filters.FilterSet):
class Meta:
model = Author
fields = ["articles","age","hometown"]
view.py
class AuthorListView(ExportMixin,SingleTableMixin,FilterView):
model=Author
table_class = authorTable
template_name = 'app/dashboard.html'
filterset_class = AuthorFilter
table_pagination = {"per_page": 10}
这给了我一个看起来像的过滤器:
文章:
- (对象 1)
- (对象 2)
- (对象 3)
我似乎也无法执行反向表/过滤器。如果我创建一个文章表和一个文章过滤器,我似乎无法获取或过滤作者对象。
我已经阅读了这两个文档几天了,但似乎不明白。任何建议将不胜感激!提前致谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)