Answer the question
In order to leave comments, you need to log in
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)
Model2
How can I add links to all objects
when creating a new class object Model1
? Model2
save 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())
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question