V
V
vhsporno2019-06-04 21:23:28
Django
vhsporno, 2019-06-04 21:23:28

How to save a form into multiple objects?

There is a model in which ssh data is stored:

class Volumion(models.Model):
  name = models.CharField(max_length=50)
  hostname = models.CharField(max_length=50)
  port = models.IntegerField()
  user = models.CharField(max_length=30)
  password = models.CharField(max_length=30)
  is_online = models.BooleanField(default=False)

There is a model that stores files that are on a specific ssh:
class Files(models.Model):
  volumio = models.ForeignKey(Volumion, on_delete = models.CASCADE)
  file = models.FileField(upload_to='uploads/')
  name = models.CharField(max_length=100, blank=True, null=True)

Purpose: upload a file to several ssh at once.
How can I make sure that when submitting the form, several objects with different volumio_id are created at once?
That is, the file and the name are the same, but the volumio_id is different.
if form.is_valid():
      for vol in Volumion.objects.filter(is_online=True):
        new = form.save(commit=False)
        new.volumio_id = vol.id
        new.set_name()
        new.save()

Doesn't work, saves only the last object

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vhsporno, 2019-06-04
@vhsporno

ids = [p.id for p in Volumion.objects.filter(is_online=True)]
      new = form.save(commit=False)
      new.volumio_id = ids[0]
      new.set_name()
      new.save()
      for id in ids[1:]:
        Files.objects.create(volumio_id=id, file=new.file, name=new.name)

Implemented like this

F
FulTupFul, 2019-06-04
@FulTupFul

Crutch solution
In the form, we write a method that duplicates the creation:

def save_duplicate(self, volumion):
    volumion.id = None
    volumion.save()
    Files.objects.create(**self.cleaned_data, volumio=volumion)

In the view:
from copy import deepcopy

if form.is_valid():
      for vol in Volumion.objects.filter(is_online=True):
        new = form.save(commit=False)
        new.volumio_id = vol.id
        new.set_name()
        new.save()
        new.save_duplicate(deepcopy(vol))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question