Check that the selected fields of a many-to-many relationship do not overlap

I am trying to create a condition that must be met before an object can be stored in the database. I have table A and table B, A has 2 separate many-to-many relationships with B. I am trying to check if the condition is that these fields being treated as sets are non-overlapping targets before saving the record.

Here's 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 am getting the error

"<Foo: None>" must have a value for field "foo" before many-to-many relationships can be used.

I assume he wants it to be saved before I make this comparison, but the whole point is not to save it to the database until that condition is true. How to do it right?

+3


source to share


1 answer


The Model method save

does not have access to m2m related fields because it is called before them. If you want to check them, you must define a custom model form for your class FooAdmin

(assuming you are using django admin) and do this check 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

      

+1


source







All Articles