Gio*_*lia 345 python django django-models
有没有办法在Django中定义几个字段是唯一的?
我有一个卷(期刊)表,我不想要同一期刊的一个卷号.
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
Run Code Online (Sandbox Code Playgroud)
我试图unique = True在字段中添加属性journal_id,volume_number但它不起作用.
Jen*_*ens 575
有一个简单的解决方案叫做unique_together,它可以完全满足您的需求.
例如:
class MyModel(models.Model):
field1 = models.CharField(max_length=50)
field2 = models.CharField(max_length=50)
class Meta:
unique_together = ('field1', 'field2',)
Run Code Online (Sandbox Code Playgroud)
在你的情况下:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
unique_together = ('journal_id', 'volume_number',)
Run Code Online (Sandbox Code Playgroud)
daa*_*awx 45
UniqueConstraint与该constraints选项一起使用。与相比unique_together,它提供的功能更多,将来可能会不推荐使用。
例如:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
]
Run Code Online (Sandbox Code Playgroud)
Sup*_*ova 15
在 Django 4.0 中,
UniqueConstraint() 的新 *expressions 位置参数支持在表达式和数据库函数上创建功能唯一约束。例如:
from django.db import models
from django.db.models import UniqueConstraint
from django.db.models.functions import Lower
class MyModel(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
class Meta:
constraints = [
UniqueConstraint(
Lower('first_name'),
Lower('last_name').desc(),
name='first_last_name_unique',
),
]
Run Code Online (Sandbox Code Playgroud)
是的,您可以使用 Django 类 Meta 将多个字段定义为唯一字段,如下例所示:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
unique_together = ('volume_number', 'journal_id')
Run Code Online (Sandbox Code Playgroud)
注意:
为了使事情能够写入,您不应将属性添加unique=True到您在属性中定义的任何字段unique_together,否则它将无法作为唯一的一起工作。