class Book(models.Model):
    shelf = models.ForeignKey(Shelf, blank=True, null=True, related_name=
        'in_shelf')


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
django - inline - Поиск существующей записи вместо добавления новой