Django:如何根据管理页面中的类别排列产品

时间:2019-04-02 02:04:14

标签: django

在管理页面中,我有两个模型:类别和产品。 打开“产品”模型时,我会看到各个产品的列表。

如何根据类别对产品进行分类?

The "directory structure" of what I'm currently getting:

Categories (Model Root)
|
----Footwear
----Topwear

Products (Model Root)
|
----T-shirt
----Sneakers
----Jacket
----Boots



The "directory structure" of what I want to get:

Categories (Model Root)
|
----Footwear
----Topwear

Products (Model Root)
|
----Footwear
    |
    ----Sneakers
    ----Boots
----Topwear
    |
    ----T-shirt
    ----Jacket

1 个答案:

答案 0 :(得分:0)

您可以定义模型,如下所示

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

class Product(models.Model):
   name = models.CharField(max_length=150)
   category = models.ForeignKey(Category, on_delete=models.CASCADE)

   class Meta:
    ordering = ['category']
    verbose_name = 'Category'
    verbose_name_plural = 'Categories'

如果您想查看特定类别的所有产品,可以尝试一下

Class ProductInLine(admin.TabularInline): 
   """ Your code here """ 

class CategoryAdmin(admin.ModelAdmin): 
   """ Your code here """ 
   inlines = [ProductInLine]

使用此选项,您可以查看特定类别的所有产品