在一对多关系模型中动态过滤对象

时间:2013-07-29 17:26:10

标签: django django-models django-views django-urls

我想访问属于特定课程的内容列表。我应该如何编写我的观点和网址来访问它。我已经为课程列表编写了观点和网址,但有些内容无法获取每门课程内容

from django.contrib.auth.models import User
from django.db import models
import datetime 
from django.utils import timezone
from django.template.defaultfilters import slugify



class PostManager(models.Manager):
    def live(self):
        return self.model.objects.filter(published=True)



class Course(models.Model):
    course_name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, blank=True, default='')
    pub_date = models.DateTimeField('date published')
    author = models.ForeignKey(User, related_name="courses")
    published_course = models.BooleanField(default=True)
    objects = PostManager()

    class Meta:
        ordering = ["-pub_date", "course_name"]

    def __unicode__(self):
        return self.course_name

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date < now

    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently ?'   

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.course_name)
        super(Course, self).save(*args, **kwargs)

    @models.permalink   
    def get_absolute_url(self):
        return ("course:detail", (), {"slug": self.slug})


class Content(models.Model):
    course = models.ForeignKey(Course)
    topic_name = models.CharField(max_length=200)
    slug_topic_name = models.SlugField(max_length=200, blank=True, default='')
    desc = models.TextField()
    published = models.BooleanField(default=True)
    objects = PostManager()

    def __unicode__(self):
        return self.topic_name

    def save(self, *args, **kwargs):
        if not self.slug_topic_name:
            self.slug_topic_name = slugify(self.topic_name)
        super(Content, self).save(*args, **kwargs)

    @models.permalink   
    def get_absolute_url(self):
        return ("content:detail", (), {"slug_topic_name": self.slug_topic_name})

我的课程/ views.py

from django.views.generic import ListView, DetailView

from .models import Course, Content


class CourseListView(ListView):
    model = Course

    def get_queryset(self):
        queryset = super(CourseListView, self).get_queryset()
        return queryset.filter(published_course=True)

class CourseContentListView(ListView):

    context_object_name = 'content_list'
    queryset = Content.objects.filter(course__course_name='HTML5')
    template_name = 'content/content_list.html'

我的课程/ urls.py

from django.conf.urls import patterns, url

from . import views

urlpatterns = patterns('',
    url(r"^$", views.CourseListView.as_view(), name="list" ),
    url(r"^(?P<course_name>[\w-]+)/$", views.CourseContentListView.as_view(), name="list"),
)

项目/ urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin


from . import views

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'kodeworms.views.home', name='home'),
    # url(r'^kodeworms/', include('kodeworms.foo.urls')),
    url(r"^$", views.HomepageView.as_view(), name="home"),
    url(r"^course/", include("course.urls", namespace="course")),
    url(r"^course/content", include("course.urls", namespace="content")),   

    url(r'^admin/', include(admin.site.urls)),
)

项目\当然\模板\当然\ course_list.html

{% extends "_layouts/base.html" %}
{% load url from future %}

{% block page_title %}Course List | {% endblock %}

{% block page_content %}
<h2>Course Grid</h2>

<ul>
    {% for course in course_list %}
    <li><a href="{% url 'content:list' %}">{{ course.course_name }}</a></li>
    {% empty %}
    <li>Sorry, no courses yet. Check back soon! </li>
    {% endfor %}
    <p><a href="{% url 'home' %}">&larr; Home</a></p>
</ul>
{% endblock %}

项目\当然\模板\内容\ content_list.html

{% extends "_layouts/base.html" %}

{% block page_title %}{{ course.course_name }} | {% endblock %}


{% block page_content %}
<h2>{{ course.course_name }}</h2>
{{ course.content|linebreaks }}

<ul>
    {% for content in object_list %}
    <li>{{ content.topic_name }}</li>
    {% empty %}
    <li>Sorry, no content yet. Check back soon! </li>
    {% endfor %}
</ul>

<p><a href="{% url 'course:list' %}">&larr; Course List</a></p>
{% endblock %}

在上面的代码中,我已经为其内容硬编码了课程名称。我希望动态地获取任何任意课程。另外我的pk = 1给出错误,pk = 8/9/10有值。有人可以帮忙吗

3 个答案:

答案 0 :(得分:0)

a = Course.objects.get(pk=1)
# List of contents for this course
course_contents = a.content_set.all()

答案 1 :(得分:0)

好的,这是我的第一个Web项目,并且是在民意调查应用之后的第一个Django项目。所以这个解决了。适合那些像我一样的初学者/编程/ web-dev世界。

我的pk是从pk = 8开始的,所以我无法弄清楚如何使用它访问内容列表。但是随着一些Django文档的阅读和回答Link,我能够找出问题,并通过它解决问题。无论如何,这里修改了代码

views.py - &gt;之前该课程是硬编码的,以访问内容列表,我也试图用主键动态访问内容(我没有成功)。所以现在我尝试用slug访问它并且成功了。

class CourseContentListView(ListView):

    template_name = 'course/content_list.html'

    def get_queryset(self):
        self.course = get_object_or_404(Course, slug=self.kwargs['slug'])
        return Content.objects.filter(course=self.course, published=True)

我还从官方文档中了解了更多关于Django模板的信息,并找出了命名和访问网址的正确方法,并对course_list.html进行了更改以访问内容列表

course_list.html

<ul>
    {% for course in course_list %}
    <li><a href="{% url 'course:content_list' course.slug %}">{{ course.course_name }}</a></li>
    {% empty %}
    <li>Sorry, no courses yet. Check back soon! </li>
    {% endfor %}
    <p><a href="{% url 'home' %}">&larr; Home</a></p>

</ul>

更改了urls.py以正确指向相应的网址

my urls.py

urlpatterns = patterns('',
    url(r"^$", views.CourseListView.as_view(), name="list" ),
    url(r"^(?P<slug>[\w-]+)/$", views.CourseContentListView.as_view(), name="content_list"),
)

我还在学习,所以上面的代码可能会出错,甚至更好/更优雅。但话说回来,这段代码对我有用。

答案 2 :(得分:0)

您应该将CourseContentListView更改为:

class CourseContentListView(ListView):

    model = Content
    context_object_name = 'content_list'
    template_name = 'content/content_list.html'

    def get_queryset(self):
        queryset = super(CourseContentListView, self).get_queryset()
        course_name = self.kwargs.get('course_name')
        course = Course.objects.get(course_name=course_name)
        queryset = queryset.filter(course=course)
        return queryset