使用自相关外键复制Django模型实例

时间:2018-10-07 12:36:05

标签: python django web django-models django-views

一直试图让它在没有运气的情况下工作多年。我有3个模型

class Project(models.Model):
    number = models.CharField(max_length=30, unique=True)
    title = models.CharField(max_length=300)
    client = models.CharField(max_length=300)
    category = models.CharField(max_length=300, null=True)
    .
    .
    etc

class ProjectGroup(models.Model):
    description = models.CharField(max_length=300)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    group = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
    .
    .
    etc

class ProjectPart(models.Model):
    number = models.CharField(max_length=30)
    description = models.CharField(max_length=300)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    group = models.ForeignKey(ProjectGroup, null=True, blank=True, 
    on_delete=models.CASCADE)
    .
    .
    etc

项目包含许多组,这些组又包含项目部分。这些组可以包含类似于文件夹结构的其他组。

我正在尝试复制一个项目实例,该项目实例将复制组和零件的所有相关实例并保持文件夹类型结构。

到目前为止,我有..

def copyprojectview(request, project_id):
    form = CopyProjectForm(request.POST)
       if form.is_valid():

           #get details for new project and create              

           number = form.cleaned_data['number']
           title = form.cleaned_data['title']
           client = form.cleaned_data['client']
           category = form.cleaned_data['category']

           project = Project.objects.create(number=number, title=title, client=client, category=category)

           # get list of groups and parts to be copied to new project

           parts = ProjectPart.objects.filter(project_id=project_id)
           groups = ProjectGroup.objects.filter(project_id=project_id)

然后这就是我要坚持的地方。复制并尝试保持正确的关系。我可以复制没有这样的组的所有部分

           for part in parts:
               part.pk = None
               part.group = None
               part.project = project
               part.save()

这将复制所有部分并将它们放在新项目的顶层。

我也希望能够复制组并将零件复制到这些组。

用这个把我的头发拉出来!

0 个答案:

没有答案