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

标签 python django

我需要在单个页面/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/

相关文章:

python manage.py makemigrations 没有检测到任何变化?

Django - ModelForm 创建还是更新?

python - 如何重命名包名称

python - Pandas 高效 VWAP 计算

python - 无法在 django 中加载配置文件

python - 如何抓取需要使用 Python 登录的网站

python - 有没有一种简单的方法可以在 python 中自定义 try- except 错误代码输出?

python - 随着时间的推移,Django 查询变得越来越慢

python - 将 OpenCV 与 Django 结合使用

python - 仅当需要更新时才更新 django 模型中的字段