如何从网址中的不同模型获取 slug,即路径(<slug:slug1>/<slug:slug2>/)?

How to get slugs from different models in the urls i.e path(<slug:slug1>/<slug:slug2>/)?

我正在尝试获取类似于 WWW.domain.com/slug1/slug2 的 ur 模式,其中 slug1 是要插入的外键。可以把它想象成 library.com//。作者和书是两个不同的模型,都有自己的鼻涕虫。有没有一种方法可以将作者的 slug 导入到图书的详细视图,然后在图书详细视图的 url 中使用它?

这就是我想象中的路径:

    path('brands/<slug:brand_slug>/<slug:model_slug>', views.Brand_ModelsDetailView.as_view(), name='model-detail'),

这些是我的模型:

class Brand(models.Model):
    brand_name = models.CharField(
        max_length=50, help_text='Enter the brand name',)  
    slug = AutoSlugField(populate_from='brand_name', default = "slug_error", unique = True, always_update = True,)


    def get_absolute_url(self):
        """Returns the url to access a particular brand instance."""
        return reverse('brand-detail', kwargs={'slug':self.slug})

    def __str__(self):
        return self.brand_name

class Brand_Models(models.Model):
    name = models.CharField(max_length=100)
    brand = models.ForeignKey('Brand', on_delete=models.SET_NULL, null=True)
    slug = AutoSlugField(populate_from='name', default = "slug_error_model", unique = True, always_update = True,)


    def get_absolute_url(self):
        """Returns the url to access a particular founder instance."""
        return reverse('model-detail', kwargs={'slug':self.slug})

    def __str__(self):
        return self.name

我目前尝试的观点:

class Brand_ModelsDetailView(generic.DetailView):
    model = Brand_Models


    def get_queryset(self):
        qs = super(Brand_ModelsDetailView, self).get_queryset()
        return qs.filter(
            brand__slug=self.kwargs['brand_slug'],
            slug=self.kwargs['model_slug']
        )

编辑:

class RefrenceDetailView(generic.DetailView):
   model = Refrence

   def get_queryset(self):
       qs = super(RefrenceDetailView, self).get_queryset()
       return qs.filter(
            brand__slug=self.kwargs['brand_slug'],
            model__slug=self.kwargs['model_slug'],
        slug = self.kwargs['ref_slug']
    )

你的错误是Brand_Models的get_absolute_url方法;因为细节 URL 需要两个 slug,所以你需要将它们都传递给那里的 reverse

return reverse('model-detail', kwargs={'brand_slug': self.brand.slug, 'model_slug':self.slug})