擅长:python、mysql、java
<p>向模型中添加<code>clean</code>方法,以便可以编辑现有行。</p>
<pre><code>def clean(self):
queryset = MO.objects.exclude(id=self.id).filter(slug=self.slug)
if self.foreign_key is None:
if queryset.exists():
raise ValidationError("A row already exists with this slug and no key")
else:
if queryset.filter(foreign_key=self.foreign_key).exists():
raise ValidationError("This row already exists")
</code></pre>
<p>注意,<code>clean</code>(或<code>full_clean</code>)不是由默认的<code>save</code>方法调用的。</p>
<p>注意:如果将此代码放在<code>save</code>方法中,则更新表单(如在管理中)将不起作用:由于<code>ValidationError</code>异常,将出现回溯错误。</p>