メモ〜cleaned_dataと外部キー


今回の結論

ModelFormクラスが外部キー由来のフィールドを持っている場合、cleaned_dataにもprimary-keyではなくインスタンスそのものが入る。

具体例

models.py
class Book(models.Model):
  title = models.CharField(max_length=30)
  author = models.Foreign_key(Author, on_delete=models.CASCADE)
forms.py
class BookForm(ModelForm):
  class Meta:
    fields = "__all__"

  def clean_author(self):
    author = self.cleaned_data.get("author") # ここにはインスタンスそのものが入っている
    if author.pk == 1:
      raise forms.ValidationError("テストユーザーを著者として登録しないでください")
    return author