N
N
NyxDeveloper2021-09-16 15:53:00
Django
NyxDeveloper, 2021-09-16 15:53:00

How to add m2m connection for multiple objects in Django?

There are two models

class Model1(models.Model):
    name = models.CharField(max_length=100)
    models2 = models.ManyToManyField("app.Model2")

class Model2(models.Model):
    name = models.CharField(max_length=100)


Model2How can I add links to all objects when creating a new class object Model1?
I tried to override the Model2save method on the model:
def save(self, *args, **kwargs):
        if not self.id:
            super(Model2, self).save(*args, **kwargs)
            self.model1_set.add(*self.model1_set.model.objects.all())

But it doesn't work.
Tell me what to do, I can not find anything useful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NyxDeveloper, 2021-09-16
@NyxDeveloper

def save(self, *args, **kwargs):
        if not self.id:
            super(Model2, self).save(*args, **kwargs)
            self.model1_set.add(*self.task_set.model.objects.values_list("id", flat=True))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question