1
我有一個Django模型,如下所示:在Django的模型deg_course_cat表Django的模型和MPTT整合
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class deg_course_cat(models.Model):
degree_code = models.CharField(max_length=24)
specialization = models.CharField(max_length=48)
category_level1 = models.CharField(max_length=48)
category_level2 = models.CharField(max_length=96)
category_level3 = models.CharField(max_length=48)
min_credit = models.IntegerField()
max_credit = models.IntegerField()
primarystuff = models.CharField(max_length=24)
class deg_course_cat_mptt(MPTTModel):
name = models.CharField(max_length=100, unique=False)
min_credit = models.IntegerField(null=True)
max_credit = models.IntegerField(null=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['name']
# Create your models here.
的數據如下所示:
我想根據模型及其數據創建mptt結構,即類似於以下結構:
我該如何解決這個問題?由於我對python很陌生,如果我能夠實現這一目標,那將會很棒。
我試圖像下面的一些代碼,但我不知道它是如何正確的是:
from studentapp.models import deg_course_cat, deg_course_cat_mptt
#degreeroot = deg_course_cat_mptt.objects.create(name="DegreeRoot")
for degrees in deg_course_cat.objects.values_list('degree_code', flat=True):
degreearray = set(deg_course_cat.objects.values_list('degree_code', flat=True))
for i in range(0,len(degreearray)):
degree(i) = deg_course_cat_mptt.objects.create(name= degreearray(i), parent=degreeroot)
for categories_l1 in deg_course_cat.objects.values_list('category_level1', flat=True):
category_level1 = set(deg_course_cat.objects.values_list('category_level1', flat=True))
for categories_l2 in deg_course_cat.objects.values_list('category_level2', flat=True):
category_level2 = set(deg_course_cat.objects.values_list('category_level2', flat=True))
for categories_l3 in deg_course_cat.objects.values_list('category_level3', flat=True):
category_level3 = set(deg_course_cat.objects.values_list('category_level3', flat=True))