我有以下类别模型:
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 :(得分: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)
我仍然觉得应该有更优雅的方式,所以请随时贡献。谢谢!