简体   繁体   English

Django 为同一子类别生成多个 url

[英]Django generating multiple urls for the same subcategory

In my app, there's a list of categories and subcategories with a ForeignKey relationship.在我的应用程序中,有一个具有 ForeignKey 关系的类别和子类别列表。 Say, there're:说,有:

  • Subcategory1 related to Category1与 Category1 相关的 Subcategory1
  • Subcategory2 related to Category2与 Category2 相关的 Subcategory2

I expect to get the following subcategory urls:我希望获得以下子类别网址:

These urls work fine.这些网址工作正常。 However, django also generates these urls that I don't need:但是,django 也会生成这些我不需要的网址:

Why do they appear in my app?为什么它们会出现在我的应用程序中? How do I get rid of them?我该如何摆脱它们? Thanks in advance!提前致谢!

models.py:模型.py:

class Category(models.Model):
    categoryslug = models.SlugField(max_length=200, default="",unique=True)

    def get_absolute_url(self):
        return reverse("showrooms_by_category",kwargs={'categoryslug': str(self.categoryslug)})

class Subcategory(models.Model):
    subcategoryslug = models.SlugField(max_length=200, default="",unique=True)
    category = models.ForeignKey('Category', related_name='subcategories', 
    null=True, blank=True, on_delete = models.CASCADE)

    def get_absolute_url(self):
        return reverse("showrooms_by_subcategory",
        kwargs={'categoryslug': str(self.category.categoryslug), 'subcategoryslug': str(self.subcategoryslug)})

views.py:视图.py:

class ShowroomCategoryView(DetailView):
    model = Category
    context_object_name = 'showrooms_by_category'
    template_name = "website/category.html"
    slug_field = 'categoryslug'
    slug_url_kwarg = 'categoryslug'


class ShowroomSubcategoryView(DetailView):
    model = Subcategory
    context_object_name = 'showrooms_by_subcategory'
    template_name = "website/subcategory.html"
    slug_field = 'subcategoryslug'
    slug_url_kwarg = 'subcategoryslug'

urls.py:网址.py:

urlpatterns = [
    path('<slug:categoryslug>/<slug:subcategoryslug>/', views.ShowroomSubcategoryView.as_view(), name='showrooms_by_subcategory'),
    path('<slug:categoryslug>/', views.ShowroomCategoryView.as_view(), name='showrooms_by_category'),
]

I think the reason for this is foreign_key .我认为原因是foreign_key So, I think as you can use one to one field to get the target, like:因此,我认为您可以使用一对一的字段来获取目标,例如:

subcategoryslug = models.SlugField(max_length=200, default="",unique=True)
category = models.OneToOneField('Category', related_name='subcategories',null=True, blank=True, on_delete = models.CASCADE)

*Note:- Please understand the logic too behind it. *注意:- 请理解其背后的逻辑。 For that, do research more.为此,做更多的研究。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM