Search code examples
djangovalidationmany-to-manyunique

Django ManyToManyField Validate Unique Set


models.py

class MyProduct(models.Model):
    name = models.CharField()
    codes = models.ManayToManyField(Code)

Hi, I'm trying to validate the ManyToManyField for the unique set. it shoud validate that similar set should not repeat again on another record, In the django docs , it mentioned clearly that ManyToManyField cannot be unique=True or unique_together. So how can I handle this validation, I am not able to find the solution for this. I request please guide me for some suggestion for this, it will be helpfull for me. Thanks in advance.


Solution

  • This is the reference to Array field: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/

    Sample Codes :
    Model

    class Code(models.Model):
    id=models.AutoField(primary_key=True)
    codevalue=models.CharField(max_length=50)
    def __str__(self):
        return f"{self.codevalue}"
    from django.contrib.postgres.fields import ArrayField
    class MyProduct(models.Model):
          name = models.CharField(max_length=50)
          codes=models.ManyToManyField(Code)
          codesarray = ArrayField(models.CharField(max_length=50, blank=True, 
          null=True),size=8, blank=True, null=True)
    

    form

    class MyProductForm(forms.ModelForm):
        class Meta:
            model=MyProduct
            fields='__all__'
    

    view

    from .forms import CodeForm, MyProductForm
    from EntityInformation.models import MyProduct
    class MyProductView(View):
      template_name = 'EntityInformation/Detail/MyProduct.html'
    
    def get(self, request, name=None):
        myproductform=MyProductForm()
        return render(request, self.template_name, {'form': myproductform})
    def post(self,request, name=None):
        myproductform=MyProductForm(request.POST)    
        if myproductform.is_valid():       
    
            cleaneddata= myproductform.cleaned_data
    
            arr =[]
            for val in cleaneddata['codes']:
                arr.append(val)        
            try:
                myproductdoc=MyProduct.objects.get(codesarray = arr)
            except:
                myproductdoc=None
    
            if myproductdoc is None:
                newproductdoc = myproductform.save(commit=False)
                newproductdoc.codesarray=arr
                myproductform.save()
                return render(request, self.template_name, {'form': myproductform})
            else:
                print("Unique validation error")
    

    Above code should help you