Home > Mobile >  How to add data to a ManyToMany field model?
How to add data to a ManyToMany field model?

Time:02-08

I have model Department:

class Department(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=30)
    subsidiary = models.ManyToManyField('self',null=True,blank=True, symmetrical=False, related_name='subsidiary_name')
    superior = models.ForeignKey('self',null=True,blank=True, related_name='superior_name', on_delete = models.DO_NOTHING)
    manager = models.ForeignKey(Manager, on_delete = models.DO_NOTHING)
    history = HistoricalRecords()

def get_subsidiary(self):
        return "\n".join([p.title for p in self.subsidiary.all()])

def __str__(self):
    return self.title 

In Department model I have 2 instance of the same model: subsidiary and superior departments. The rules are simple: one department can have only one superior department, and many subsidiary. I want to implement next logic: enter image description here

I am creating new department SLF, and f.e. I choose SID department as superior department for SLF. Finally, when I save SLF object I want to add this department as subsidiary for SID automatically.

I am trying to override save method like:

def save(self, *args, **kwargs):
    print('Department.objects.filter(title=self.superior): ', Department.objects.filter(title=self.superior))
    if self.superior__in == Department.objects.filter(title=self.superior.title):
        tmp = Department.objects.filter(title=self.superior.title)
        tmp.create(subsidiary = self.superior)
        tmp.save()

    super(Department, self).save(*args, **kwargs)

But it doesn't work. How can implement something like this?

CodePudding user response:

You have to use add() function to add new object to ManyToManyField. Remember also, that with filter you get QuerySet. To get object you should ust get or even get_object_or_404, but look yourself for that :)

...
    tmp = Department.objects.get(title=self.superior.title)
    tmp.subsidiary.add(self.superior)
...

You don't need to save it.

CodePudding user response:

Finally,

def save(self, *args, **kwargs):
        super(Department, self).save(*args, **kwargs)
        if self.superior == Department.objects.get(title=self.superior.title):
            tmp = Department.objects.get(title=self.superior.title)
            tmp.subsidiary.add(self)

Thank you for your advices.

  •  Tags:  
  • Related