<p>我认为带有自定义<a href="https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ManyToManyField.through" rel="nofollow noreferrer">through</a>表的<a href="https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_many/" rel="nofollow noreferrer">ManyToMany</a>关系和该表上的<a href="https://docs.djangoproject.com/en/2.0/ref/models/options/#unique-together" rel="nofollow noreferrer">unique_together</a>约束应该可以满足您的需要。在</p>
<p>示例代码:</p>
<pre><code>from django.db.models import Model, ForeignKey, ManyToManyField, CharField
class Option(Model):
name = CharField()
class Thing(TimeStampedModel):
options = ManyToManyField("Option", through="ThingOption")
class ThingOption(Model):
thing = ForeignKey(Thing)
option = ForeignKey(Option)
value = CharField()
class Meta:
unique_together = ('thing', 'option')
</code></pre>
<p>对于Django 2.2+建议使用<a href="https://docs.djangoproject.com/en/2.2/ref/models/constraints/#django.db.models.UniqueConstraint" rel="nofollow noreferrer">UniqueConstraint</a>。在文档中有一个<a href="https://docs.djangoproject.com/en/2.2/ref/models/options/#unique-together" rel="nofollow noreferrer">note</a>声明<code>unique_together</code>将来可能会被弃用。请参阅<a href="https://stackoverflow.com/questions/2881043/django-create-a-unique-database-constraint-for-2-or-more-fields-together">this</a>帖子了解其用法。在</p>