2017-04-19 64 views
0

新增模式,我有以下分类模型:树为了无限深度从列表

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

正如你可以看到,该类别可以通过ForeignKey的有父​​类别和子类别。

现在假设我有这样的名单:

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可以找到两次。而且,树的最大深度也不是。

+0

所以我很困惑。问题是什么? – raiderrobert

+0

我需要保存与其父类别相关的每个单独类别。例如:保存类别网络与母公司技术与母公司杂志。 –

回答

0

我也有一个领域,我存储每个类别的完整路径。例如: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) 

我仍然觉得应该有一个更优雅的方式,所以随时贡献。谢谢!