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 - Search for existing record instead of adding a new one