gpt4 book ai didi

python - Django模型和mptt集成

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:17 24 4
gpt4 key购买 nike

我有一个如下所示的 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模型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))

最佳答案

您可以执行类似 this 的操作

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

关于python - Django模型和mptt集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22945759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com