如何基于链接到请求的slug的类别显示查询集?

2022-09-28 21:08:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图显示查询集链接到某个类别,根据网页slug要求。我在学校,试图学习Django框架

以下是我尝试过的观点:

class ProductCategoryListView(ListView):
    template_name = 'products/product_list.html'

    def get_queryset(request, *args, **kwargs):
        if Product.category == ProductCategory.title:
            instance = ProductCategory.objects.get(title=instance)
            post = Product.objects.filter(category=instance)
            return post

以下是我的模型:

class ProductCategory(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField()
    parent = models.ForeignKey('self', blank=True, null=True,
                related_name='children', on_delete=models.PROTECT)

class Product(models.Model):
    title       = models.CharField(max_length=100)
    category    = models.ForeignKey(ProductCategory, null=True, blank=True,
                    on_delete=models.CASCADE)
    slug        = models.SlugField(blank=True)
    description = models.TextField()
    price       = models.DecimalField(decimal_places=2, max_digits=6)
    image       = models.ImageField(upload_to='products/', null=True, blank=True)

此视图加载了网页,但未呈现任何查询


Tags: instancenametrue网页titlemodelsproductnullmaxclassproductsslugblankcategoryproductcategory
1条回答
网友
1楼 ·

假设slug是一个类别,您可以这样做:

from django.shortcuts import get_object_or_404


class ProductCategoryListView(ListView):
    template_name = 'products/product_list.html'

    def get_queryset(request, *args, **kwargs):
        category = get_object_or_404(Category, slug=self.slug)
        products = Product.objects.filter(category=category)
        return products

Product模型中,您可以在category字段中设置一个related_name,这样就更容易从category访问产品:

class Product(models.Model):
    title       = models.CharField(max_length=100)
    category    = models.ForeignKey(
        ProductCategory, null=True, blank=True, related_name="products", on_delete=models.CASCADE
    )
    ...

现在您可以这样做:

from django.shortcuts import get_object_or_404


class ProductCategoryListView(ListView):
    template_name = 'products/product_list.html'

    def get_queryset(request, *args, **kwargs):
        category = get_object_or_404(Category, slug=self.slug)
        return category.products.all()

热门问题