在django中为多个字段添加唯一键

时间:2018-04-13 06:41:17

标签: django django-models

我有以下模特

class SettingAttributes(Core):
    attribute_name = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    setting_type = models.CharField(max_length=10, choices=SETTING_TYPES)

    class Meta:
        app_label = 'core'

class SettingAttrValue(Core):
    attribute_value = models.CharField(max_length=200)
    attribute_type = models.CharField(max_length=200)
    attribute = models.ForeignKey(SettingAttributes)
    user = models.ManyToManyField(User)
    avaliases = models.TextField()
    attriblob = models.BinaryField(default=None, blank=True, null=True)

    class Meta:
        app_label = 'core'

我想在unique_togetherSettingAttrValue上添加User。如果我在第二个模型的元类中执行此操作,django会给出类似'unique_together' refers to a ManyToManyField 'user', but ManyToManyFields are not permitted in 'unique_together'.

的错误

1 个答案:

答案 0 :(得分:0)

unique_together添加到intermediate模型:

class SettingAttrValue(Core):
    attribute_value = models.CharField(max_length=200)
    attribute_type = models.CharField(max_length=200)
    attribute = models.ForeignKey(SettingAttributes)
    user = models.ManyToManyField(User, through='UserSettingAttrValue')
    avaliases = models.TextField()
    attriblob = models.BinaryField(default=None, blank=True, null=True)

    class Meta:
        app_label = 'core'


class UserSettingAttrValue(models.Model):
    setting_attr_value = models.ForeignKey(SettingAttrValue)
    user = models.ForeignKey(User)

    class Meta:
        unique_together = ('setting_attr_value', 'user')