我遇到了与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年是有效的,但现在不行了。在
谢谢你的帮助!在
目前没有回答
相关问题 更多 >
编程相关推荐