LoginSignup
0
0

More than 1 year has passed since last update.

メモ〜cleaned_dataと外部キー

Posted at

今回の結論

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0