django - ListView中如何根据ForeignKey的主键创建动态过滤器?
问题描述
我对 Django 比较陌生,但我现在面临的主要问题是创建一个 ListView,它将根据我的 ForeignKey 的主键显示上传的文档。
我尝试了几种方法来尝试创建过滤器并阅读有关基于类的视图的在线文档,但它似乎没有关于如何在我的过滤器中使用我的 ForeignKey 主键的相关信息。
这些是我的模型:
class Post(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(default = 'default0.jpg',
upload_to='course_image/')
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=6)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.IntegerField(default = 0)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk' : self.pk})
class Lesson(models.Model):
title = models.CharField(max_length=100)
file = models.FileField(upload_to="lesson/pdf")
date_posted = models.DateTimeField(default=timezone.now)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('lesson_upload', kwargs={'pk': self.pk})
这是我的 ListView 过滤器不起作用:
class LessonListView(ListView):
model = Lesson
template_name = 'store/uploaded_lesson.html'
context_object_name = 'lesson'
# def get_queryset(self):
# return Lesson.objects.filter(Post__pk=self.Post.pk)
def get_queryset(self):
self.post__pk = get_object_or_404(post__pk,
name=self.kwargs['post__pk'])
return Lesson.objects.filter(post__pk=self.post__pk)
这是我的 urls.py:
path('post/<int:pk>/lesson_uploaded/', LessonListView.as_view(), name='lesson_uploaded'),
这是我的html:
{% extends "store/base.html" %}
{% block content %}
<div id="main">
<table class="table mb-0">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Download</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for lesson in lesson %}
<tr>
<td>
{% if lesson.file %}
<img src="{{ lesson.file.url }}" style="width:100px;">
{% else %}
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
解决方案
你可以这样尝试:
在网址中,添加post_id
:
path('lessons/<int:post_id>/', LessonListView.as_view()),
然后更新 View 以获取post_id
inget_queryset
方法:
class LessonListView(ListView):
model = Lesson
template_name = 'store/uploaded_lesson.html'
context_object_name = 'lesson'
def get_queryset(self):
return Lesson.objects.filter(post_id=self.kwargs.get('post_id'))
另外,请不要在 for 循环中命名列表和该列表的项目相同,因此将其更新为:
{% for l in lesson %}. // or anything other than lesson
<tr>
<td>
{% if l.file %}
推荐阅读
- python-3.x - 我有一列 URL,但我只能提取其中一个 URL 的数据
- sql-server - (从表中选择 *)来自另一台没有链接服务器的电脑
- r - (RIM)R中的加权样本
- flutter - Flutter 在其他 dart 文件中更改 bool(使用 setState)
- node.js - NodeJS:为什么我的 POST 请求不起作用?
- three.js - 我是threejs的初学者-如何将此着色器(使用gl_fragcoord)转换为几何体的材质以产生相同的效果?
- powershell - foreach 循环问题(组合命令)
- c# - 总阶段 I2C
- javascript - 如何将包含日期的一维数组划分为几个较小的数组(二维数组)
- javascript - 使用参数调用父函数