如何在一个页面上显示两个Django模型?

时间:2013-08-25 20:21:09

标签: django

我想创建一个显示两个独立Django模型的页面:

class Client(models.Model):
    name = models.CharField(max_length=100)
    slug = AutoSlugField(populate_from='name', blank=True, unique=True)
    order = models.IntegerField(editable=False, default=0)

    class Meta:
        ordering = ('order',)
    def __unicode__(self):
        return self.name

class Press(models.Model):
    title = models.CharField(max_length=50)
    article = models.ImageField(upload_to = 'images')

    def image_thumb(self):
        if self.article:
            return u'<img src="%s" height="125"/>' %self.article.url
        else:
            return "no image"

    image_thumb.short_description = "article"
    image_thumb.allow_tags = True

    class Meta:
        verbose_name_plural = "press"

我不确定如何在Views.py中编写我的查询集。我尝试过这样的事情......

class ClientView(generic.ListView):    
    template_name = 'clients.html'
    context_object_name = 'client'

    def queryset(request):
        client_page = {'press': Press.objects.all(), 'client': Clients.objects.all()}
        return client_page

然后在我的urls.py中...

url(r'^clients/', views.ClientView.as_view(), name = 'client_model'),

我在堆栈答案中读到我可以使用&#34; get_extra_context&#34;但有人能告诉我这是怎么用的吗?

1 个答案:

答案 0 :(得分:2)

class ClientView(generic.ListView):
    # ...

    def get_context_data(self, **kwargs):
        context = super(ClientView, self).get_context_data(**kwargs)
        context['press'] = Press.objects.all()
        return context