gpt4 book ai didi

Django 在基于类的通用 ListView 中过滤子对象

转载 作者:行者123 更新时间:2023-12-02 17:41:01 26 4
gpt4 key购买 nike

大家好!

我的应用程序使用了基于 Django 类的通用 ListView 。我有两个模型对象:通过外键链接的 Books 和 Publishers(下面的代码)。我想使用 ListView 向出版商展示他们的图书,但过滤图书(只获取当前用户拥有的活跃图书)

附加信息:如果可能的话,我不想在模板中使用过滤器。附加信息 2:我无法通过模型类中的定义使用过滤器,因为我需要访问请求对象

代码

模型.py

class Publisher(models.Model):
name = models.CharField(max_length=255)

class Book(models.Model):
name = models.CharField(max_length=255)
active = models.BooleanField(default=True)
publisher = models.ForeignKey(Publisher, related_name='books')
owner = models.ForeignKey(User)

View .py

class ListBooksByPublisher(ListView):
model = Publisher
template_name = 'list.html'
context_object_name = 'books'

列表.html

{% for publisher in publishers %}
{{ publisher.name }}
{% for book in publisher.books.all %}
{{ book.name }}
{% endfor %}
{% endfor %}

非常感谢任何帮助!

最佳答案

你需要覆盖get_queryset View 上的方法返回您的自定义查询集

例如:

class ListBooksByPublisher(ListView):
....
def get_queryset(self):
return self.model.objects.filter(blablabla))

希望对你有帮助

关于Django 在基于类的通用 ListView 中过滤子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20687735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com