首页 文章

Django在基于类的通用列表视图中过滤子对象

提问于
浏览
1

大家好日子!

我的应用程序使用了基于django类的通用列表视图 . 我有两个模型对象:通过外键链接的图书和发布者(下面的代码) . 我想使用ListView向发布商展示他们的图书,但过滤图书(只获取当前用户拥有的有效图书)

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

models.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)

views.py

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

list.html

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

任何帮助非常感谢!

3 回答

  • -2

    您需要覆盖视图上的get_queryset方法以返回自定义查询集

    例如:

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

    希望这可以帮助

  • 0

    您可以编写自定义过滤器,该过滤器返回发布者的书籍列表 .

    yourapp / templatetags / my_filters.py:

    from django import template
    register = template.Library()
    
    @register.filter
    def get_books(publisher):
        return publisher.book_set.filter(YOUR_CUSTOM_FILTER)
    

    你的模板:

    {% load get_books from my_filters %}
    ...
    {% for publisher in publishers %}
        {{ publisher.name }}
        {% for book in publisher|get_books %}
            {{ book.name }}
        {% endfor %}
    {% endfor %}
    

    另一种方法是将额外的数据传递给您的视图:

    class ListBooksByPublisher(ListView):
        ...
        def get_context_data(self, **kwargs):
            context = super(ListBooksByPublisher, self).get_context_data(**kwargs)
            context['publishers_with_books'] = your_custom_data_structure
            return context
    
  • 7
    #views
    class ListBooksByPublisher(ListView):
        model = Publisher
        template_name = 'list.html'
        context_object_name = 'publishers'
    #tmp
    {% for publisher in publishers %}
        {{ publisher.name }}
        {% for book in publisher.book_set.all %}
            {{ book.name }}
        {% endfor %}
    {% endfor %}
    

相关问题