我对一个列强制了一个唯一的约束,由于该约束是在整个表上强制的,所以有没有办法根据外键使一个列唯一
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)
例如 我创建了2个bucket(bucket 1和bucket 2)
创建了以下bucketlists
>>> Bucketlist.objects.create(bucket=bucket1, name='bucketlist1')
>>> Bucketlist.objects.create(bucket=bucket1, name='bucketlist2')
正在尝试在bucket 2中创建bucketlist1
>>> Bucketlist.objects.create(bucket=bucket2, name='bucketlist1')
IntegrityError: duplicate key value violates unique constraint "myapp_bucketlist_name"
看起来您希望
Bucketlist
上的name
字段是唯一的,但仅适用于那些属于相同Bucket
的对象为此,您可以查看Django的
unique_together
元选项(documentation)在您的情况下,它看起来像:
注意从
name
字段中删除了unique=True
相关问题 更多 >
编程相关推荐