我对列强制执行唯一约束,并且由于在整个表上强制执行约束,是否有办法根据外键使列唯一?
class Bucket(models.Model):
"""This class represents the bucket model"""
title = models.CharField(max_length=255, blank=False, unique=True)
class Bucketlist(models.Model):
"""This class represents the bucketlists model"""
bucket = models.ForeignKey(Bucket, on_delete=models.CASCADE,
related_name='bucketlists')
name = models.CharField(max_length=255, blank=False, unique=True)
E.g 我创建了2个桶(桶1和桶2)
创建了以下桶列表
>>> Bucketlist.objects.create(bucket=bucket1, name='bucketlist1')
>>> Bucketlist.objects.create(bucket=bucket1, name='bucketlist2')
尝试在存储桶2中创建bucketlist1
>>> Bucketlist.objects.create(bucket=bucket2, name='bucketlist1')
IntegrityError: duplicate key value violates unique constraint "myapp_bucketlist_name"
答案 0 :(得分:2)
您希望name
上的Bucketlist
字段是唯一的,但仅适用于属于同一Bucket
的那些对象。
为此,您可以查看Django的unique_together
Meta选项(documentation)。
在你的情况下,它看起来像:
class Bucketlist(models.Model):
"""This class represents the bucketlists model"""
bucket = models.ForeignKey(Bucket, on_delete=models.CASCADE,
related_name='bucketlists')
name = models.CharField(max_length=255, blank=False)
class Meta:
unique_together = (("bucket", "name"),)
请注意从unique=True
字段中删除name
。