I'm trying to validate a model with a ManyToManyField
pointed at a parent model to be unique within a grandparent model. It's fine if different grandparents have grandchildren of the same name, but a grandparent may not have two grandchildren of the same name.
This question Discusses a solution if the relationships are ForignKey
s, but that doesn't work here. The GrandChild has to be saved before I can reference the parents to test to see if it's unique within a GrandParent.
Since the Parents can't be attached until the GrandChild exists, how can the uniqueness of a GrandChild be validated against the GrandParent?
class GrandParent(models.Model):
name = models.CharField(max_length=255)
class Parent(models.Model):
name = models.CharField(max_length=255)
grandparent = models.ForeignKey(GrandParent)
class Meta:
unique_together('name', 'GrandParent')
class GrandChild(models.Model):
name = models.CharField(max_length=255)
parents = models.ManyToManyField(Parent)
def validate_unique(self, exclude=None):
# validate that GrandChild is unique within a given GrandParent
I tried adding the save()
method to the grandchild method
def save(self, *args, **kwargs):
grand_parent = self.parents.all()[0].grandparent
grand_children = [child for child in parent.grandchild_set.all() for parent in grandparent.parent_set.all()]
for grand_child in grand_children:
if grand_child.name == self.name and grand_child != self:
raise IntegrityError("must be unique")
But this gave the IntegrityError
ValueError: "<GrandChild: name>" needs to have a value for field "grandchild" before this many-to-many relationship can be used.