pythonDjango在许多字段中防止重复

2024-04-25 19:08:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三节课模型.py-在

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表-

^{pr2}$

我的问题是我希望“Nx2FwComponentWithPath”多对多字段是唯一列表,即在下面我不应该允许添加nx2componentwithpath两次-

(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])

在多对多集合中要求唯一性合理吗?你能建议一个更好的方法来实现这一点吗?在


Tags: name列表modelmodelslengthmaxpdbclass
1条回答
网友
1楼 · 发布于 2024-04-25 19:08:04

为您的多人关系使用自定义模型

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似乎表明):

^{pr2}$

相关问题 更多 >