2017-04-19 68 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) 

我仍然覺得應該有一個更優雅的方式,所以隨時貢獻。謝謝!