Django-如何控制和过滤相关对象

时间:2019-07-19 03:05:49

标签: django django-select-related django-related-manager

我有两个模型

注意::为了使问题变得简单,我删除了一些代码

class Categories(models.Model):
    category_name           = models.CharField(max_length=100, null=True)

class Courses(models.Model):
    course_name             = models.CharField(max_length=200)
    category                = models.ForeignKey(Categories, on_delete = models.CASCADE,)

例如,如果我有3个类别(PHP,Python,Javascript),并且该类别中的每个类别都有与此相关的课程

PHP = php_course1, php_course2, php_course3

Python = python_course1, python_course2, python_course3

Javascript = javascript_course1, javascript_course2, javascript_course3

因此,当有人单击任何类别时,我想要的是将他带到仅包含与此类别相关课程的页面。

我为做到这一点所做的一切

views.py

class CategoriesListView(ListView):
   model               = Categories
   template_name       = 'category_list.html'
   context_object_name = 'category_list'

class CategoriesDetailView(DetailView):
   model               = Categories
   template_name       = 'category_detail.html'
   context_object_name = 'category_detail'

第一个模板“ category_list.html”

{% for category in category_list %}

  <a href="{% url 'category' category.slug %}" class="btn">{{ category.category_name }}</a>

{% endfor %}

第二个模板“ category_detail.html”

{% for course in category_detail.courses_set.all  %}

  <h1> {{ course.course_name }} </h1>

{% ednfor %}

例如,如果我单击“ javascript类别”,这将很好地工作,它将仅显示“ javascript课程”。

问题是我想过滤课程,但是因为我使用了这样的相关对象,所以我在视图上没有上下文,因此我可以玩

所以我做的方法是错误的,这就是为什么它限制了我,还有另一种好方法让我告诉你,或者这是一种好方法,我可以做一些事情来过滤和播放与“课程”对象

我搜索并发现了这一点,但这不仅给我所有的“课程”,而且还与特定的“类别”相关

def get_context_data(self, **kwargs):
    context = super(CategoriesDetailView, self).get_context_data(**kwargs)
    context['course'] = Courses.objects.all().select_related("category")
    return context

1 个答案:

答案 0 :(得分:1)

您必须filter Courses模式才能按照您的类别获得课程。

您必须在视图中使用类似的查询:

def get_context_data(self, **kwargs):
    context = super(CategoriesDetailView, self).get_context_data(**kwargs)
    context['course'] = Courses.objects.filter() # Your filter query here
    return context

现在,您的过滤查询可以基于您捕获kwargs的{​​{1}}。

如果您正在捕获a,则过滤器查询将为:

url