如何将两个模型传递给基于类的通用视图 [英] How can I pass two models to a class based generic view

查看:137
本文介绍了如何将两个模型传递给基于类的通用视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做博客的应用程序,它有一个名为Entry的模型。我使用基于类的通用来查看此条目,我很高兴。



现在,另一个名为Eventapp的应用程序有一个称为事件的模型。现在我想查询这个模型的几个事件,然后发送到上面提到的类的泛型。我如何做到这一点?



这是我在 urls.py 到目前为止查看条目模型:

  urlpatterns = patterns('',

url(r'^ $',ArchiveIndexView .as_view(
model = Entry,paginate_by = 5,date_field ='pub_date',template_name ='homepage.html'),
),

url(r'^ ?P<年> \d {4})/(P<一个月> [AZ] {3})/(P<?天> \w {1,2})/(P<蛞蝓> \\ \\ w +)/ $',
DetailView.as_view(model = Entry,queryset = Entry.objects.all(),slug_field ='slug')),)
/ pre>

有没有办法将事件模型传递给 ArchiveIndexView.as_view() DetailView.as_view()不知何故?

解决方案

看起来像我一样将您的活动放在多个页面上,一个上下文处理器可能是您正确的工具。它应该允许您在每个模板的上下文中访问事件的查询:

  from eventapp.models import Event 

def event_provessor(request):
return {'events':Event.objects.all()}

由于查询器的懒惰,您不必害怕在不需要列表的情况下打数据库,所以只有在事件



当然你也可以例如。将视图子类化并将事件添加到上下文中,但如果多个视图受影响,上下文处理器可能会更有意义!


I have an app called "blog" that has a model called "Entry". I use a class based generic to view this Entry and I am happy with this.

Now, along comes another app called "Eventapp" that has a model called "Event". Now I want to query this model for a few events, and then send it to the class based generic mentioned above. How do I do this?

Here is what I have in my urls.py so far to view the Entry model:

urlpatterns = patterns('',

    url(r'^$', ArchiveIndexView.as_view(
        model=Entry, paginate_by=5, date_field='pub_date',template_name='homepage.html'),
        ),

   url(r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>\w+)/$', 
     DetailView.as_view(model=Entry, queryset=Entry.objects.all(), slug_field='slug')),)

Is there a way to pass the Event model to ArchiveIndexView.as_view() and DetailView.as_view() somehow?

解决方案

As it looks to me you would like to have your events on more than one page, a context processor may be the right tool for you. It should allow you to access a queryset of events within the context of every template:

from eventapp.models import Event

def event_provessor(request):
    return {'events': Event.objects.all()}    

Because of the queryset's laziness you don't have to be afraid to hit the database if you don't need the list, the query is only run if you would iterate over events.

Of course you could also eg. subclass the views and add the events there to the context, but if more than one view is affected a context processor might make more sense!

这篇关于如何将两个模型传递给基于类的通用视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆