gpt4 book ai didi

python - 有没有办法在 2 个字段上创建一个唯一的 id?

转载 作者:行者123 更新时间:2023-12-03 01:00:44 25 4
gpt4 key购买 nike

这是我的模型:

class GroupedModels(models.Model):
other_model_one = models.ForeignKey('app.other_model')
other_model_two = models.ForeignKey('app.other_model')

本质上,我想要的是 other_model 在这个表中是唯一的。这意味着,如果存在 other_model_one id 为 123 的记录,我不应允许使用 other_model_two id 创建另一条记录 123。我猜我可以覆盖 clean 但我想知道 django 是否有内置的东西。

我正在使用 PSQL 2.2.5 版本。

编辑:这并不是一个独特的情况。如果我添加一条包含 other_model_one_id=1 和其他 other_model_two_id=2 的记录,我应该无法添加另一条包含 other_model_one_id=2 的记录,并且其他other_model_two_id=1

最佳答案

我在这里解释了几个选项,也许其中一个或组合对您有用。

覆盖保存

您的约束是业务规则,您可以重写 save 方法以保持数据一致:


class GroupedModels(models.Model):
# ...
def clean(self):
if (self.other_model_one.pk == self.other_model_two.pk):
raise ValidationError({'other_model_one':'Some message'})
if (self.other_model_one.pk < self.other_model_two.pk):
#switching models
self.other_model_one, self.other_model_two = self.other_model_two, self.other_model_one
# ...
def save(self, *args, **kwargs):
self.clean()
super(GroupedModels, self).save(*args, **kwargs)

更改设计

我放了一个易于理解的示例。让我们假设这种情况:

class BasketballMatch(models.Model):
local = models.ForeignKey('app.team')
visitor = models.ForeignKey('app.team')

现在,您希望避免一支球队与自己进行比赛,而且 A 队只能与 B 队比赛一次(几乎是您的规则)。您可以将模型重新设计为:

class BasketballMatch(models.Model):
HOME = 'H'
GUEST = 'G'
ROLES = [
(HOME, 'Home'),
(GUEST, 'Guest'),
]
match_id = models.IntegerField()
role = models.CharField(max_length=1, choices=ROLES)
player = models.ForeignKey('app.other_model')

class Meta:
unique_together = [ ( 'match_id', 'role', ) ,
( 'match_id', 'player',) , ]

ManyToManyField.对称

这看起来像 symetrical问题,django 可以帮你处理。无需创建 GroupedModels 模型,只需在 OtherModel 上创建一个 ManyToManyField 字段即可:

from django.db import models
class OtherModel(models.Model):
...
grouped_models = models.ManyToManyField("self")

这就是 django 为这些场景内置的内容。

关于python - 有没有办法在 2 个字段上创建一个唯一的 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com