[Answered ]-Python Django prevent duplicate in Many-to-many fields

2👍

use a custom model for your ManyToMany Relation

class Nx2FwComponent(models.Model):
    name = models.CharField(max_length=10)

class Nx2FwComponentWithPath(models.Model):
    name = models.ForeignKey(Nx2FwComponent)
    path = models.CharField(max_length=100, unique=True)


class Rel(models.Model):
    nx2FwConfig = models.ForeignKey('Nx2FwConfig')   
    nx2FwComponentWithPath = models.ForeignKey(Nx2FwComponentWithPath)

    class Meta:
         unique_together = ('nx2FwConfig', 'nx2FwComponentWithPath')

class Nx2FwConfig(models.Model):
    nx2FwComponentWithPaths = models.ManyToManyField(Nx2FwComponentWithPath, through=Rel)

but Maybe what you want is (the unique in path seems indicate that):

class Nx2FwComponent(models.Model):
    name = models.CharField(max_length=10)

class Nx2FwComponentWithPath(models.Model):
    name = models.ForeignKey(Nx2FwComponent)
    nx2FwConfig = models.ForeignKey('Nx2FwConfig')         
    path = models.CharField(max_length=100, unique=True)

    class Meta:
         unique_together = ('nx2FwConfig', 'name')

class Nx2FwConfig(models.Model):
    nx2FwComponents = models.ManyToManyField(Nx2FwComponent, through=Nx2FwComponentWithPath)
👤sax

Leave a comment