django - 带有条件 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。
解决方案
您可以自定义查询集;
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 匹配的对象过滤。
推荐阅读
- flutter - Flutter packages get 不安装新包
- javascript - 如何将某事物推送到返回数组的函数?(是否可以推送到返回数组的函数)
- php - 如何获取SQL语句的行数
- java - 解压输入请求
- python - 最大连续的
- php - 如何将文档根目录更改为脚本的公共目录?
- ios - SpriteKit 驾驶技巧
- asp.net - 在 Modalpopupextender 内的 Datalist 按钮中未触发
- c++ - 顺序必要的正则表达式脚本的时间复杂度更高?
- bash - 在 ubuntu / Linux 中从 Shell 脚本(启动)运行 GamingAnywhere