clean()得到了一个意想不到的关键字参数' validate_unique'

时间:2015-08-02 21:44:57

标签: 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)

这里的想法是基本上防止表格中的字段排列按此处详细输入Prevent permutations of foreign keys in Django

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

1 个答案:

答案 0 :(得分:4)

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

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

def clean(self):
   ...
   super(TwoPlanetKeyword, self).clean()

有关详细信息,请参阅validating objects上的文档。