clean() 得到了一个意外的关键字参数“validate_unique”

New*_*wtt 0 python django

我在 Django 中有一个模型如下

class TwoPlanetKeyword(models.Model):
    planet_one = models.ForeignKey(Planet, related_name="planet_one")
    planet_two = models.ForeignKey(Planet, related_name="planet_two")
    keyword_list = models.TextField(max_length=100000)

    class Meta:
        verbose_name = 'Keywords for Two Planet Combination'
        unique_together = ['planet_one', 'planet_two']

    def __str__(self):
        return "Keywords for two planet combination of {} and {}".format(self.planet_one, self.planet_two)

    def clean(self, *args, **kwargs):
        plan_one = self.planet_one
        plan_two = self.planet_two
        try:
            obj_val = TwoPlanetKeyword.objects.get(Q(planet_one=plan_one, planet_two=plan_two) | Q(planet_one=plan_two, planet_two=plan_one))
            raise ValidationError({
                        NON_FIELD_ERRORS: [
                            'This combination exists',
                        ],
                    })
        except TwoPlanetKeyword.DoesNotExist:
            super(TwoPlanetKeyword, self).clean(*args, **kwargs)

    def full_clean(self, *args, **kwargs):
        return self.clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(MyModel, self).save(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

这里的想法是基本上防止表中字段的排列被输入,如这里详述的防止 Django 中的外键排列

这解决了上述问题,但是clean() got an unexpected keyword argument 'validate_unique'当我尝试在 Django Admin 的表中保存新条目时,它给了我一个错误

Ala*_*air 5

您应该删除该full_clean方法。它并不是真的被设计为被覆盖。这个想法是你编写一个自定义的清理方法(正如你所做的那样),然后当你调用 时obj.full_clean(),基本实现会调用obj.clean()你。

请注意,clean()它不接受任何 args 或 kwargs,因此您可以将它们从签名中删除。您的错误是因为您将validate_unique关键字参数 from传递full_clean给超类的 clean 方法。

def clean(self):
   ...
   super(TwoPlanetKeyword, self).clean()
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅有关验证对象的文档。