Python Django防止多对多字段中的重复

时间:2014-12-11 23:28:38

标签: python django many-to-many

我的models.py中有3个类 -

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 Nx2FwConfig(models.Model):
    nx2FwComponentWithPaths = models.ManyToManyField(Nx2FwComponentWithPath)

我创建了一个列表对象以添加到Nx2FwConfig表 -

(Pdb) nx2CompList
[<Nx2FwComponentWithPath: V:\rels\mba\mba>, <Nx2FwComponentWithPath: v:\rels\mfw\mfw>]

我遇到的问题是我想要&#34; Nx2FwComponentWithPath&#34;多对多字段是唯一的列表,即在下面我不应该被允许两次添加nx2CompList -

(Pdb) nx21 = Nx2FwConfig()
(Pdb) nx21.save()
(Pdb) nx21.nx2FwComponents.add(nx2CompList[0], nx2CompList[1])
(Pdb) nx22 = Nx2FwConfig()
(Pdb) nx22.save()
(Pdb) nx22.nx2FwComponents.add(nx2CompList[0], nx2CompList[1])

在多对多集中要求唯一性是否合理?能否请您提出更好的实施方法?

1 个答案:

答案 0 :(得分:2)

为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)

但也许你想要的是(路径中的unique似乎表明了这一点):

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)