<h2>姜戈2.2+</h2>
<p>使用<a href="https://docs.djangoproject.com/en/2.2/ref/models/options/#django.db.models.Options.constraints" rel="noreferrer">^{<cd1>}</a>功能<a href="https://docs.djangoproject.com/en/2.2/ref/models/constraints/#django.db.models.UniqueConstraint" rel="noreferrer">^{<cd2>}</a>比一起使用<strong>唯一性更受欢迎。</p>
<p>来自Django文档中的<a href="https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together" rel="noreferrer">^{<cd3>}</a>:</p>
<blockquote>
<p>Use UniqueConstraint with the constraints option instead.<br/>
UniqueConstraint provides more functionality than unique_together.<br/>
unique_together may be deprecated in the future.</p>
</blockquote>
<p><strong>例如:</strong></p>
<pre><code>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')
]
</code></pre>