我正在尝试使用Django制作标准的博客文章Web应用程序。我在一个应用程序中有多个模型。我想在所有模型的几条帖子中显示一个索引,为此我需要在每个模型的视图中包含多个queryset,我不知道该怎么做。
博客/models.py
class topicone(models.Model):
title = models.CharField(max_length=200)
date = models.DateTimeField()
def __str__(self):
return self.title
class topictwo(models.Model):
title = models.CharField(max_length=200)
date = models.DateTimeField()
def __str__(self):
return self.title
class topicthree(models.Model):
title = models.CharField(max_length=200)
date = models.DateTimeField()
def __str__(self):
return self.title
博客/urls.py
urlpatterns = [
path('', views.indeview.as_view(), name="indexview"),
path('<int:pk>', DetailView.as_view(
model = topicone,
template_name = "blogs/topicone.html"
)),
]
blog / views.py
class indeview(ListView):
model = topicone
template_name = "blog/index.html"
def get_queryset(self):
return topicone.objects.all()
views.py完全没有用,因为我在这里只使用一种模型。我尝试编写一个不继承自任何其他通用视图的独立视图,因此我可以创建不同的上下文并在视图中传递多个字典,但这似乎行不通。这是我试图解决的方法
blogone = topicone.objects.all()
blogdict = {
'id': blogone
}
blogtwo = topictwo.objects.all()
blog2dict = {'id': blogtwo}
return render (request, 'blog/index.html', blogdict, blogtwo)
此视图仅显示来自一个模型的数据, blogtwo
您应该考虑以下内容:
blogone = topicone.objects.all()
blogtwo = topictwo.objects.all()
return render(request, 'blog/index.html', {'blogone': blogone, 'blogtwo': blogtwo})
由于渲染PARAMS是request
,template
和context
。
参考:https : //docs.djangoproject.com/en/2.0/topics/http/shortcuts/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句