【问题标题】:I have a problem that I could not fetch product details by category我有一个问题,我无法按类别获取产品详细信息
【发布时间】:2022-10-02 22:30:01
【问题描述】:

我有一个问题,我无法按类别获取产品详细信息 因为 Views 包含两个变量,我无法让它们显示产品详细信息

模型

from django.db import models

# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=200)
    slug = models.CharField(max_length=200)


def __str__(self):
    return self.name

class Product(models.Model):
    Category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=False, blank=False)
    slug = models.CharField(max_length=200, null=False, blank=False)
    description = models.TextField(max_length=350, null=False, blank=False)
    image = models.ImageField( null=False, blank=False)
    quantity = models.IntegerField(null=False, blank=False)


def __str__(self):
    return self.name

网址

path(\'category/<str:product_category_slug>/<str:product_slug>/\', views.product_detail, name=\"product-detail\")

维维斯

def product_detail(request, product_category_slug=None, product_slug=None):
    #How do I get product details through this path that contains a category and then the product

我希望有一个人可以帮助我

    标签: django django-views


    【解决方案1】:
    def product_detail(request, product_category_slug, product_slug):
        product = Product.objects.get(slug=product_slug, Category__slug=product_category_slug)
        if product:
           return product
        else: 
           return "Product not found"
    

    我希望这将返回带有类别的项目对象。 要获取类别详细信息,假设您想要获取类别名称及其 slug,您可以执行以下操作: 类别名称为product.Category.name,slug 为product.Category.slug

    【讨论】:

      【解决方案2】:

      你可以这样做

      def get_product_details(request, category_slug, slug):
          # Change <Category> field name to <category> 
          product = get_object_or_404(Product, category__slug=category_slug, slug=slug)
          context = dict(product=product)
          return response(response, "product_detail.html", context)
      

      或者这样:

      def get_product_details(request, category_slug, slug):
           try:
                product = Product._default_manager.get(category__slug=category_slug, slug=slug)
           except Product.DoesNotExist:
                product = None
          context = dict(product=product)
          template_name = "product_404_template.html" if product is None else "product_detail.html"
          return response(response, template_name, context)
      

      对于这两种情况,您仍然需要处理 404

      【讨论】:

        猜你喜欢
        • 2015-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-11
        • 1970-01-01
        • 2016-12-05
        • 1970-01-01
        相关资源
        最近更新 更多