简而言之:我有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
似乎在2014年有效,但现在却没有。
我很感激你的帮助!