0

我有这 4 个模型。有一个部分,用户可以查看所有未完成的任务。我将如何使用 ListView 和 DetailView 显示这些?在 django 文档中的所有示例中,他们总是只给出一个模型的示例。这可以使用 CBV 完成还是有替代方案?

楷模

class task_a(models.Model):
    created_by = models.ForeignKey('auth.User')
    task_complete = models.BooleanField(default=0)
    q1 = models.CharField(max_length=60)
    q2 = models.DateField()
    q3 = models.TimeField()
    q4 = models.TextField()

    class Meta:
        verbose_name_plural = "task_a"
    def get_absolute_url(self):
        return reverse('task_a')
     def __unicode__(self):
        return u'%s %s %s %s %s' % (self.q1, self.q2, self.q3, self.q4,self.q5)


class task_b(models.Model):
    created_by = models.ForeignKey('auth.User')
    task_complete = models.BooleanField(default=0)
    q1 = models.CharField(max_length=60)
    q2 = models.DateField()
    q3 = models.TimeField()
    q4 = models.TextField()

    class Meta:
        verbose_name_plural = "task_b"
    def get_absolute_url(self):
        return reverse('task_b')
     def __unicode__(self):
        return u'%s %s %s %s %s' % (self.q1, self.q2, self.q3, self.q4,self.q5)


class task_c(models.Model):
    created_by = models.ForeignKey('auth.User')
    task_complete = models.BooleanField(default=0)
    q1 = models.CharField(max_length=60)
    q2 = models.DateField()
    q3 = models.TimeField()
    q4 = models.TextField()

    class Meta:
        verbose_name_plural = "task_c"
    def get_absolute_url(self):
        return reverse('task_c')
     def __unicode__(self):
        return u'%s %s %s %s %s' % (self.q1, self.q2, self.q3, self.q4,self.q5)


class task_d(models.Model):
    created_by = models.ForeignKey('auth.User')
    task_complete = models.BooleanField(default=0)
    q1 = models.CharField(max_length=60)
    q2 = models.DateField()
    q3 = models.TimeField()
    q4 = models.TextField()

    class Meta:
        verbose_name_plural = "task_d"
    def get_absolute_url(self):
        return reverse('task_d')
     def __unicode__(self):
        return u'%s %s %s %s %s' % (self.q1, self.q2, self.q3, self.q4,self.q5)
4

1 回答 1

3

您可以通过覆盖get_context_data()类中的函数来添加额外的上下文变量:

class MultipleModelsListView(ListView):
    model = TaskA # Class names should use capitalized CamelCase

    def get_context_data(self, **kwargs):
        kwargs = super(MultipleModelListView, self).get_context_data(**kwargs)
        kwargs.update({
            'taskb_list': TaskB.objects.all(), # or with some filter applied
            'taskc_list': TaskC.objects.all(),
            'taskd_list': TaskD.objects.all(),
        })
        return kwargs

除了 a 提供的默认上下文之外,这将为您提供ListView上下文变量taskb_listtaskc_listtaskd_list进行迭代。

您可以像这样在模板中迭代这些:

{% for task in object_list %} {# default supplied by ListView #}
    {{ task.whatever }}
{% endfor %}
{% for task in taskb_list %}
    {{ task.whatever }}
{% endfor %} 
{# etc. #}
于 2013-08-13T07:40:32.393 回答