我有两个类似的类,查询过滤器是县代码DE或NL。
是否可以基于url名称进行对象过滤并仅保留一个类?例如,如果我将浏览器指向
127.0.0.1:8000/germany
django将调用过滤器
feed__country__name =' DE'
和
127.0.0.1:8000/netherland
将使用
feed__country__name =' NL'?
我的网址:
url(r'^netherland/$', NLFeedList.as_view(), name='nl'),
url(r'^germany/$', DEFeedList.as_view(), name='de'),
视图:
class NLFeedList(PaginationMixin, ListView):
model = FeedItem
template_name = 'nl_feed.html'
context_object_name = 'feed_items'
paginate_by = 20
def get_queryset(self):
items = FeedItem.objects.filter(feed__country__name='NL')
if self.kwargs.get('category', None):
return items.category(self.kwargs.get('category'))
return items
def get_context_data(self, **kwargs):
context = super(NLFeedList, self).get_context_data(**kwargs)
context['categories'] = Category.objects.filter(country__name='NL')
return context
class DEFeedList(PaginationMixin, ListView):
model = FeedItem
template_name = 'de_feed.html'
context_object_name = 'feed_items'
def get_queryset(self):
items = FeedItem.objects.filter(feed__country__name='DE')
if self.kwargs.get('category', None):
return items.category(self.kwargs.get('category'))
return items
def get_context_data(self, **kwargs):
context = super(DEFeedList, self).get_context_data(**kwargs)
context['categories'] = Category.objects.filter(country__name='DE')
return context
答案 0 :(得分:1)
您可以执行以下操作:
<强> urls.py 强>
url(r'^(?P<country>germany|netherland)/$', FeedList.as_view(), name='feedlist')
和视图:
class FeedList(PaginationMixin, ListView):
model = FeedItem
context_object_name = 'feed_items'
match = {'germany':'DE','netherland':'NL'}
def get_queryset(self):
code = self.match[self.kwargs['country']]
items = FeedItem.objects.filter(feed__country__name=code)
self.template_name = '%s_feed.html' % code.lower()
if self.kwargs.get('category', None):
return items.category(self.kwargs.get('category'))
return items
def get_context_data(self, **kwargs):
context = super(FeedList, self).get_context_data(**kwargs)
context['categories'] = Category.objects.filter(country__name=self.match[self.kwargs['country']])
return context
此外,您可能不需要两个模板,只需要一个,在这种情况下,只需删除此行self.template_name = '%s_feed.html' % code.lower()
并相应地设置template_name
。
答案 1 :(得分:0)
将您的网址更改为
url(r'^(?P<country>netherland|germany)/$', NLFeedList.as_view(), name='nl'),
然后使用
在视图中访问此新<country>
参数
country = self.kwargs['country']
然后在您的视图中执行必要的if country = '...':
代码块。