基于类的视图django多重slu

时间:2016-09-14 17:53:10

标签: django django-class-based-views

我有cbt generic listview我希望过滤两个slu ..但是slug_url_kwargs只允许传递单个字符串。如何更新slug_url_kwarg以支持多个slug?或者我还能做什么?

所以我有这个模型和视图功能

class SaityProfile(models.Model):
    user = models.ForeignKey(User, default=0)
    about = models.CharField(max_length=255, blank=True)
    name = models.CharField(max_length=255)
    url = models.CharField(max_length=255, unique=True)

    def __unicode__(self):
        return self.name 
class Saity(models.Model):
    profile = models.ForeignKey('SaityProfile', null=True)
    user = models.ForeignKey(User, null=True)
    name = models.CharField(max_length=250)
    url = models.CharField(max_length=250, default=gen_slug_page)
    desc = models.CharField(max_length=250, blank=True)
    order = models.IntegerField(default=1)

    def get_absolute_url(self):
        return reverse('sites:website_pages', kwargs={'website_slug': self.url})
class WebsitesProfileList(generic.ListView):
    model = Saity
    slug_field = 'url'
    slug_field_kwargs = 'profile_url'
    template_name = 'saity_ds/websites_profile_list.html'

    def get_context_data(self, **kwargs):
        self.profile = SaityProfile.objects.get(url=self.kwargs['profile_url'])
        extra_context = {
            'profile': self.profile 
        }
        context =  super(WebsitesProfileList, self).get_context_data(**kwargs)
        context.update(extra_context)
        return context

我的代码看起来很像。我想添加新功能。我选择了基于类的视图,我认为这是我的错误,因为它不清楚

1 个答案:

答案 0 :(得分:0)

您根本不需要设置slug_url_kwarg。只需覆盖get_queryset并返回您希望视图显示的查询集。

class WebsitesProfileList(generic.ListView):
    def get_queryset(self):
        return Saity.objects.filter(url=self.kwargs['url'], profile=self.kwargs['profile'])  # You will probably have to change this
    ...