DJANGO使用子类别创建类别

时间:2018-10-29 15:28:48

标签: python django

我对要尝试实现的类别表感到困惑。我正在建立一个具有多个类别级别的项目,但是我想做的是建立一个多层类别结构。

例如,我创建了具有以下类别的类,但是我想按照以下示例实现多级类别

动作>(+)        惊悚片或拳击或与帮派有关的

有什么想法吗?

class Category(models.Model):
    CATEGORIES = (
        ('ACT', 'Action'),
        ('THRILLER', 'Thriller'),
        ('COM', 'Comedy'),
        ('WEST', 'Western'),
        ('MILITARY', 'Military'),
    )

    image = models.ImageField()
    description = models.CharField(max_length=500)
    quantity = models.IntegerField()
    category = models.CharField(
        max_length=10,
        choices=CATEGORIES
    )
    date_posted = models.DateTimeField(auto_now_add=True, blank=True)

2 个答案:

答案 0 :(得分:0)

使用标签包:https://djangopackages.org/grids/g/tagging/

对于您的工作,我同时使用了tagit和tagulous。两者都很好。

答案 1 :(得分:0)

您需要按以下方式更改模型。我们应该使用“亲子关系”来实现您的目标。

class Category(models.Model):
    CATEGORIES = (
        ('ACT', 'Action'),
        ('THRILLER', 'Thriller'),
        ('COM', 'Comedy'),
        ('WEST', 'Western'),
        ('MILITARY', 'Military'),
    )

    image = models.ImageField()
    description = models.CharField(max_length=500)
    quantity = models.IntegerField()
    category = models.CharField(
        max_length=10,
        choices=CATEGORIES
    )
    date_posted = models.DateTimeField(auto_now_add=True, blank=True)
    parent = models.ForeignKey('self', null=True, blank=True, related_name="childs")

访问父级和子级的示例:

parents = Category.objects.filter(parent=None)
parent =  parents[0] # create some categories before using it
childs = parent.childs.all()
相关问题