在列表中以无限深度添加树订单中的模型



我有以下类别模型:

class Category(MPTTModel):
    name = models.CharField(max_length=50)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

您可以看到,该类别可以通过外国基础具有父级类别和子类别。

现在假设我有此列表:

Magazines
Magazines/Tech
Magazines/Tech/Network
Magazines/Tech/Programming
Magazines/Tech/Programming/Python
Courses
Courses/Design
Courses/Design/Photoshop
Courses/Tech
Courses/Tech/Programming

我需要保存与父母类别相关的每个单个类别。请注意,仅检查第一个父类别还不够,因为可以找到两次../Tech/Programming。另外,树没有最大的深度。

我也有一个字段,我在其中存储了每个类别的完整路径。例如: Magazines/Tech/Programming

因此,使用它,我循环浏览列表,并检查是否有一个具有相同全部路径的类别。如果没有,请与父母一起存储。狂欢代码基本上是这样:

def AddCategory(channel, category):
channel = Channel.objects.get(name='Walmart')
if len(category)> 1: # If it's not a root category
    try:
        categoria = Category.objects.get(fullpath=category[0] + "/" + category[1])
        print(categoria.name)
    except ObjectDoesNotExist:
        parent = Category.objects.get(fullpath=category[0])
        new_category = Category.objects.create(name=category[1], channel=channel, parent=parent)
        print(new_category.fullpath)
else: # If it's a root category
    try:
        categoria = Category.objects.get(fullpath=category[0])
    except ObjectDoesNotExist:
        new_category = Category.objects.create(name=category[0], channel=channel)
        print(new_category)

我仍然觉得应该有一种更优雅的方式,因此请随时做出贡献。谢谢!

最新更新