首页 > 解决方案 > 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 %}

标签: django

解决方案


你可以这样尝试:

在网址中,添加post_id

path('lessons/<int:post_id>/', LessonListView.as_view()),

然后更新 View 以获取post_idinget_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 %}

推荐阅读