德扬戈。类别和子类别

2024-04-25 23:27:02 发布

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

我想通过Django中的类别和子类别进行导航

现在我有这个:

127.0.0.1:8000/产品/最后一个子类别/产品段塞

我想做点什么

127.0.0.1:8000/产品/类别/子类别/子类别/../product slug

smth是这样的:

  • 食物
    • 蔬菜
      • 胡萝卜
      • 花椰菜
      • 西红柿
    • 果实
      • 苹果
  • 饮料

my models.py:

class Product(models.Model):
    title       = models.CharField(max_length=120)
    slug        = models.SlugField(unique=True)
    category    = models.ForeignKey('Category', on_delete=models.CASCADE) 
    description = models.TextField(blank=True,null=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Product,self).save(*args, **kwargs)

    def get_absolute_url(self):
        return self.slug

class Category(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    parent = models.ForeignKey('self',blank=True, null=True         ,related_name='child', on_delete=models.CASCADE)
    class Meta:
        unique_together = ('slug', 'parent',)    
        verbose_name_plural = "categories"   

    def __str__(self):                           
        full_path = [self.name]            
        k = self.parent
        while k is not None:
            full_path.append(k.name)
            k = k.parent

        return ' -> '.join(full_path[::-1])

我的URL.py

path('', ProductList, name='product-list1'),
path('<category_slug>/', products_by_category, name='product-categories'),

views.py

def ProductList(request):
    products = Product.objects.all()
    products = products.order_by('-publish')
    categories = Category.objects.filter(parent__isnull=True)
    context = {
        'products':products,
        'categories':categories,
    }
    template = 'products/product_list.html'
    return render(request, template ,context)


def products_by_category(request,category_slug):
    products = Product.objects.all()
    categories = Category.objects.filter(parent__isnull=True)
    slug = category_slug
    if slug:
        category_s = get_object_or_404(Category,slug = slug)    
        products = products.filter(category = category_s)
    context = {
        'products':products,
        'categories':categories,
        'category':category_s,
        'page_obj':page_obj,
    }
    template = 'products/products_by_category_list.html'
    return render(request,template,context)

以及如何显示属于同一类别的所有产品。 顺便问一下,如果按父类别排序,是否可以显示属于一个父类别的所有项目。? 比如所有的食物

  • 食物
    • 蔬菜
      • 胡萝卜
      • 花椰菜
      • 西红柿
    • 果实
      • 苹果
  • 饮料

Tags: pathnameselftrue产品modelsdefproduct
1条回答
网友
1楼 · 发布于 2024-04-25 23:27:02

听起来你想要完成的是为你的类别和子类别创建一个树状结构。有几个工具可以帮助Django更易于管理。我自己花了相当多的时间来实现这些东西,最终发现这些工具可以节省大量的时间和挫折感

出于这一目的上升到顶端的两个似乎是Django-mpttDjango-treebeard。两者都很有用,尽管有不同的优点和缺点。对我来说,我倾向于使用Django mptt,主要是因为我发现文档更全面

您可以使用mptt执行的操作示例:

models.py

...

from mptt.models import MPTTModel, TreeForeignKey

class Product(models.Model):
    title       = models.CharField(max_length=120)
    slug        = models.SlugField(unique=True)
    description = models.TextField(blank=True,null=True)
    category    = models.ForeignKey(
        'Category',
        related_name="products",
        on_delete=models.CASCADE
    ) 

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Product,self).save(*args, **kwargs)

    def get_absolute_url(self):
        return self.slug

class Category(MPTTModel):
    name = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    parent = TreeForeignKey(
        'self',
        blank=True,
        null=True,
        related_name='child',
        on_delete=models.CASCADE
    )

    class Meta:
        unique_together = ('slug', 'parent',)    
        verbose_name_plural = "categories"   

    def __str__(self):                           
        full_path = [self.name]            
        k = self.parent
        while k is not None:
            full_path.append(k.name)
            k = k.parent

        return ' -> '.join(full_path[::-1])

views.py

...

def index(request):
    if request.method == 'GET':
        category_id = int(request.GET.get('category_id', default=1))
        current_category = Category.objects.get(pk=category_id)

        children = current_category.get_children()
        ancestors = current_category.get_ancestors()
        products = current_category.products.all()

        context = {
            'categories': children,
            'current_category': current_category,
            'ancestors': ancestors,
            'products': products,
        }

    return render(request, 'your_site/index.html', context)

希望您能从索引视图中了解到,当您编写模板来显示这些信息时,这个附加上下文是多么方便。这是一个非常简单的例子,但应该提供一些想法

相关问题 更多 >