网址中有两个子弹

时间:2019-12-16 23:41:03

标签: django django-models django-views

我想要一个带有2个子段的url模式。我正在尝试使其看起来像http://127.0.0.1:8000/category/model,但在理解如何操作时遇到困难。

以下是我到目前为止的内容:

models.py

def model_detail_view(request, category_slug, model_slug):
        model = Model.objects.get(
        category__slug=category_slug, model_slug=model_slug)
    context = {
        "model": model,
    }
    return render(request=request, template_name='main/model_detail.html', context=context)

urls.py

path("<str:category_slug>/<str:model_slug>/", views.model_detail_view, name="model_detail_view"),

models.py

class Category(models.Model):
    title = models.CharField(max_length=50)
    featured_image = models.ImageField(upload_to="categories")
    category_slug = AutoSlugField(null=True, default=None,
                         unique=True, populate_from='title')

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.title

class Model(models.Model): 
    title = models.CharField(max_length=80)
    category = models.ManyToManyField(Category)
    featured_image = models.ImageField(upload_to=image_dir)
    model_slug = AutoSlugField(null=True, default=None,
                         unique=True, populate_from='title')

    class Meta:
        verbose_name_plural = "Models"

    def __str__(self):
        return self.title

1 个答案:

答案 0 :(得分:0)

尝试一下

model = model = Model.objects.get(category__category_slug=category_slug, model_slug=model_slug)


参考:

  1. Django:Lookups that span relationships---(Django Doc)