如何定义两个字段“唯一"作为情侣 [英] How to define two fields "unique" as couple
本文介绍了如何定义两个字段“唯一"作为情侣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 Django 中将几个字段定义为唯一的?
Is there a way to define a couple of fields as unique in Django?
我有一张(期刊)卷数表,但我不希望同一期刊的卷数超过一个.
I have a table of volumes (of journals) and I don't want more then one volume number for the same journal.
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)
我尝试将 unique = True
作为属性放在 journal_id
和 volume_number
字段中,但它不起作用.
I tried to put unique = True
as attribute in the fields journal_id
and volume_number
but it doesn't work.
推荐答案
有一个简单的解决方案,叫做 unique_together 完全符合您的要求.
There is a simple solution for you called unique_together which does exactly what you want.
例如:
class MyModel(models.Model):
field1 = models.CharField(max_length=50)
field2 = models.CharField(max_length=50)
class Meta:
unique_together = ('field1', 'field2',)
就你而言:
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',)
这篇关于如何定义两个字段“唯一"作为情侣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文