I'm trying to create a condition that has to be fulfilled before object can be saved to database. I have table A and table B, A has 2 separate many-to-many relations with B. I'm trying to check if condition that these fields treated as sets are disjoint holds before saving an entry.
Here is some code:
class Foo(models.Model):
first = models.ManyToManyField(Bar, related_name='first')
second = models.ManyToManyField(Bar, related_name='second')
def save(self):
if (set(self.first.all()).isdisjoint(list(self.second.all()))):
#save
else:
#raise exception
But I'm getting error
"< Foo: None >" needs to have a value for field "foo" before this many-to-many relationship can be used.
I'm guessing it wants it to be saved before I do this comparison, but the whole point is not to save it to database before this condition is true. How to do it properly?
Model save
method have no access to m2m related fields because it is called before them. If you want to validate them then you should define a custom model form for your FooAdmin
class (I suppose you're using django admin) and make this validation there.
class FooForm(forms.ModelForm):
class Meta:
model = Foo
exclude = ()
def clean():
cd = self.cleaned_data
first_objects = cd['first']
second_objects = cd['second']
# your logic
return super(FooForm, self).clean()
class FooAdmin(admin.ModelAdmin):
form = FooForm