Django模型和mptt集成

时间:2014-04-08 18:51:22

标签: python django django-models django-mptt

我有一个类似以下的django模型:

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.

django model deg_course_cat表中的数据如下所示:

enter image description here

我想基于模型及其数据创建mptt结构,例如以下结构:

enter image description here

我如何解决这个问题?因为我对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))

1 个答案:

答案 0 :(得分:1)

您可以执行this

之类的操作
category_l1_array = list(set(deg_course_cat.objects.filter(degree_code=degree[i]).values_list('category_level1', flat=True)))