简而言之:我有 2 个模型:Book
和Shelf
. 在管理表单(“添加书架”)中,我想从图书馆中已有的书籍中进行选择。默认情况下这是不可用的。
我使用了解决方案(来自上面的链接)并且一切正常,直到我尝试“保存”新对象。
错误:
未保存的模型实例 (Shelf: ShelfAlpha) 不能用于 ORM 查询。
#models.py
class Book(models.Model):
shelf = models.ForeignKey(Shelf, blank=True, null=True,
related_name="in_shelf")
#admin.py
class ShelfForm(forms.ModelForm):
class Meta:
model = Shelf
books = forms.ModelMultipleChoiceField(queryset=Book.objects.all())
def __init__(self, *args, **kwargs):
super(ShelfForm, self).__init__(*args, **kwargs)
if self.instance:
if self.instance.in_shelf:
self.fields['books'].initial = self.instance.in_shelf.all()
else:
self.fields['books'].initial = []
def save(self, *args, **kwargs):
instance = super(ShelfForm, self).save(commit=False)
self.fields['books'].initial.update(shelf=None)
self.cleaned_data['books'].update(shelf=instance)
return instance
Run Code Online (Sandbox Code Playgroud)
似乎在 2014 年工作,但现在不是。
我将不胜感激!