Django: Access the entire pk_set of pre_add and pre_remove of M2M Signal

49 Views Asked by At

I have two models Group and Child as defined below, The Group has a M2M relation to the Child.

When the m2m field children in the Group model is changed then all the add events and remove events are separated into different action

class Child(models.Model):
    name = models.CharField(max_length=100)
    req_categories = ArrayField(models.CharField(choices=Categories.choices, max_length=100))


class Group(models.Model):
    name = models.CharField(max_length=100)
    categories = ArrayField(models.CharField(choices=Categories.choices, max_length=100))
    children = models.ManyToManyField(Child, blank=True)

I want a way to access the pk_set of pre_add and pre_remove at a single place to perform some validation

currently I have a validation rule that says atleast N number of children should exist so if I place the validation on pre_remove for an action where i removed some child and added some child then the validation error will be thrown even though the upcoming pre_add action will take care of the contraint

@receiver(m2m_changed, sender=Group.children.through)
def child_models_changed(sender, instance, action, **kwargs):
    if action == "pre_add":
        do validation ....

    if action == "pre_remove":
        do validation ....
0

There are 0 best solutions below