我遇到一种情况,我想使用Meta选项unique_together来强制执行某条规则,这是中介模型:
unique_together
class UserProfileExtension(models.Model): extension = models.ForeignKey(Extension, unique=False) userprofile = models.ForeignKey(UserProfile, unique=False) user = models.ForeignKey(User, unique=False) class Meta: unique_together = (("userprofile", "extension"), ("user", "extension"), # How can I enforce UserProfile's Client # and Extension to be unique? This obviously # doesn't work, but is this idea possible without # creating another FK in my intermediary model ("userprofile__client", "extension"))
这是UserProfile:
class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) client = models.ForeignKey(Client)
谢谢。
你不能
该unique_together子句直接转换为SQL唯一索引。而且,您只能在单个表的列上设置这些值,而不能在多个表的组合上设置。
SQL
不过,您可以自己为其添加验证,只需覆盖该validate_unique方法并将此验证添加到其中即可。
validate_unique
文件:http : //docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.validate_unique