Onetomany inline select with Django admin 2018更新

2024-09-28 20:43:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了与here或{a2}相同的问题。在

简而言之:我有两个模型:Book和{}。在管理表格(“添加书架”)我想从已经在图书馆的书籍中选择。默认情况下,此选项不可用。在

我使用了这个解决方案(从上面的链接)和一切工作,直到我试图“保存”新对象。在

错误:

Unsaved model instance (Shelf: ShelfAlpha) cannot be used in an ORM query.

#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年是有效的,但现在不行了。在

谢谢你的帮助!在


Tags: instanceinselffieldsmodelmodelsargsbooks