gpt4 book ai didi

django - 用 django 形式保存新的外键

转载 作者:行者123 更新时间:2023-12-04 18:13:07 25 4
gpt4 key购买 nike

我有两个模型:

class Studio(models.Model):
name = models.CharField("Studio", max_length=30, unique=True)

class Film(models.Model):
studio = models.ForeignKey(Studio, verbose_name="Studio")
name = models.CharField("Film Name", max_length=30, unique=True)

我有一个电影表格,允许用户选择一个预先存在的工作室,或者输入一个新的:
class FilmForm(forms.Form):
studio = forms.ModelChoiceField(Studio.objects, required=False)
new_studio = forms.CharField(max_length=30, required=False, label = "New Studio Name")
name = forms.CharField(max_length=30, label = "Film Name")

有验证确保 new_studio 名称不存在。如果用户进入一个new_studio,我想先保存studio,然后再保存新的Film。
form = FilmForm(request.POST) 
if form.is_valid(): # All validation rules pass
std = Studio(name = form.cleaned_data['new_studio'])
std.save()

但是,如何将 Film 实例保存为全新的工作室 ID?我看过 this question ,但是如果我在 Film 模型和 Film Form 中有更多字段怎么办?如果我使用链接的答案,我将不得不输入每个字段:
studio = Studio.objects.get(name=request.POST['new_studio'])
newFilm=Film(name=form.name, studio=studio, field_one = form.field_one, field_two = form.field_two, etc.)

实现这一点的正确方法是什么?

最佳答案

真的,您唯一的问题是您使用了标准 Form而不是 ModelForm . Form没有 save方法,因为它本身并不与任何东西相关联(即它不知道要保存什么或保存到哪里)。

但是,如果您使用 ModelForm您需要处理在表单中创建新工作室所涉及的所有逻辑。不过,这实际上更好,因为这样您就可以只使用表单而不必担心其他任何事情:表单包含正确保存自身所需的所有逻辑。

class FilmForm(forms.ModelForm):
class Meta:
model = Film

# only need to define `new_studio`, other fields come automatically from model
new_studio = forms.CharField(max_length=30, required=False, label = "New Studio Name")

def __init__(self, *args, **kwargs):
super(FilmForm, self).__init__(*args, **kwargs)
# make `studio` not required, we'll check for one of `studio` or `new_studio` in the `clean` method
self.fields['studio'].required = False

def clean(self):
studio = self.cleaned_data.get('studio')
new_studio = self.cleaned_data.get('new_studio')
if not studio and not new_studio:
# neither was specified so raise an error to user
raise forms.ValidationError('Must specify either Studio or New Studio!')
elif not studio:
# get/create `Studio` from `new_studio` and use it for `studio` field
studio, created = Studio.objects.get_or_create(name=new_studio)
self.cleaned_data['studio'] = studio

return super(FilmForm, self).clean()

那么,在您看来,您所需要的只是:
if form.is_valid():
form.save()

关于django - 用 django 形式保存新的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8996451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com