首页 > 解决方案 > 带有条件 WHERE 的 Django3 ListView

问题描述

我在 Django 3 中有简单的 ListView:

path("show/<int:pk>", ApplicantListView.as_view(), name='applicant-list'),

我的看法如下:

class ApplicantListView(ListView):

    model = Applicant
    paginate_by = 100 
    template_name = 'applicant_list.html'

和模型

    class Work(models.Model):
        title = models.CharField(max_length=200)
        body = models.TextField()
        published = models.BooleanField(False)
        date = models.DateTimeField()
                
        def __str__ (self):
            return self.title
        
    
    class Applicant(models.Model):
        name= models.CharField(max_length=200)
        email = models.EmailField(max_length=100)
        country = CountryField(blank_label='(select country)')
        work= models.ForeignKey(Work, on_delete=models.CASCADE)
        upload = models.FileField(upload_to='up/')
        
        def __str__ (self):
            return self.name

所以我想要实现的是仅显示 URL 路径中使用的工作 ID 的申请人。目前它显示了所有记录,不考虑路径中使用的 pk。

标签: django

解决方案


您可以自定义查询集;

class ApplicantListView(ListView):

    model = Applicant
    paginate_by = 100 
    template_name = 'applicant_list.html'

    def get_queryset(self):
        qs = super().get_queryset()
        return qs.filter(work_id=self.kwargs.get('pk'))

然后,您的Applicant列表将被那些work_id与 URL 中的 ID 匹配的对象过滤。


推荐阅读