简体   繁体   English

Django:有没有办法给“unique_together”添加外键字段?

[英]Django: Is there a way to add a foreign key field to “unique_together”?

I want to be able to make a model unique on a value that comes from a foreign key model.我希望能够使模型在来自外键模型的值上独一无二。 Not sure if that's possible in django.不确定这在 Django 中是否可行。

Example: I have a model A as:示例:我有一个模型 A:

class modelA(models.Model):
    fieldA1 = models.AutoField(primary_key=True)
    fieldA2 = models.CharField(max_length=20)

And also model B as:还有模型 B 为:

class modelB(models.Model):
    fieldB1 = models.CharField(max_length=20)
    fieldB2 = models.ForeignKey(modelA)

    class Meta:
        unique_together = ('fieldB1', 'fieldB2',<<'fieldA2'>>)

I want to add fieldA2 as one of the attributes in the unique_together clause of model B. Is that possible in Django?我想将 fieldA2 添加为模型 B 的 unique_together 子句中的属性之一。这在 Django 中可行吗? I COULD NOT do it as-不能这样做-

unique_together = ('fieldB1', 'fieldB2','modelA__fieldA2')

you cannot.你不能。 database constraints cannot contain those kind of data.数据库约束不能包含这些类型的数据。 you will have to check it programmatically before creating instances or write some validator在创建实例或编写一些验证器之前,您必须以编程方式检查它

You can override modelB 's clean method like this您可以像这样覆盖modelBclean方法

class ModelB(models.Model):
    fieldB1 = models.CharField(max_length=20)
    fieldB2 = models.ForeignKey(modelA)

    def clean(self):
        """
        Validate 'fieldB1', 'fieldB2' and 'fieldB2__fieldA2' are unique together
        """
        # first, check that foreign keys fields exist. Must use '_id', or else a RelatedObjectDoesNotExist error will be raised
        if self.fieldB2_id and self.fieldB2.field_A2_id:
            if self.__class__.objects.filter(fieldB1=self.fieldB1, fieldB2=self.fieldB2, fieldB2__fieldA2=self.fieldB2.fieldA2).exists():
                raise ValidationError(
                    _('Instance of ModelB with fieldB1, fieldB2 and fieldB2.fieldA2 already exists.'),
                    code='unique_together',
                )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM