gpt4 book ai didi

python - Django - 在一页中列出许多不同的模型

转载 作者:太空宇宙 更新时间:2023-11-03 18:06:34 24 4
gpt4 key购买 nike

我需要在单个页面/url 中列出不同的模型。

#models.py
class Service(models.Model):
author = models.ForeignKey(User, related_name="services")
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)

objects = ServiceQuerySet.as_manager()

class Carousel(models.Model):
author = models.ForeignKey(User, related_name="carousels")
title = models.CharField(max_length=255)
content = models.TextField()

objects = CarouselQuerySet.as_manager()

这是我的观点,这种方式在不同的页面中列出,我尝试加入查询集,但没有成功。

#views.py

class ServiceListView(generic.ListView):
model = models.Service
queryset = models.Service.objects.published()

class CarouselListView(generic.ListView):
model = models.Carousel
queryset = models.Carousel.objects.published()

这是我的 urls.py,仅列出这些服务。

urlpatterns = patterns('',
url(r'^$', views.ServiceListView.as_view(), name="service_list"),
url(r'^$', views.CarouselListView.as_view(), name="carousel_list"),
)

我需要两个列表出现在同一页面上。我怎样才能完成这个任务?

最佳答案

通过上下文传递它怎么样?

from .models import Service,Carousel

class ServiceListView(generic.ListView):
model = Service
queryset = Service.objects.published()

def get_context_data(self, **kwargs):
context = super(ServiceListView, self).get_context_data(**kwargs)
context['carousel_list'] = Carousel.objects.published()
return context

关于python - Django - 在一页中列出许多不同的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26762053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com