dimanche 7 octobre 2018

Copying django model instances with self relating foreign keys

Been trying to get this working for ages with no luck. I have 3 models

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

A project contains a number of groups which in turn contain the project parts. The groups can contain other groups similar to a folder structure.

I am trying to copy an instance of project which will copy all related instances of groups and parts and keep the folder type structure.

so far I have..

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)

Then this is the bit I'm getting stuck on. Copying over and trying to keep the correct relationships. I can copy all the parts without the groups like this

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

This copies all the parts and puts them in the top level for the new project.

I would like to be able to copy the groups as well and have the parts copied to these groups.

Pulling my hair out with this one!




Aucun commentaire:

Enregistrer un commentaire