django-内联-搜索现有记录,而不是添加新记录 [英] django - inline - Search for existing record instead of adding a new one
问题描述
我有一个带书架和书籍的图书馆。我将每本书以一对多的关系指向一个书架。如果一本书指向 Null
,则表示该书已在图书馆中,但尚未在书架中。
I have a library with shelves and books. I point each book to one shelf in a one-to-many relationship. If a book is pointing to a Null
it means that it's in the library, but not in the shelf yet.
#models.py
class Shelf(models.Model):
pass
class Book(models.Model):
shelf = models.ForeignKey(Shelf, blank=True, null=True)
然后:
#admin.py
class BookInLine(admin.TabularInLine):
model = Book
extra = 0
class Shelf(admin.ModelAdmin):
inlines = [ BookInLine, ]
编辑书架时,我可以看到和修改该书架中的所有书籍。
When I edit the Shelf I can see and modify all the books that are in that shelf.
问题:
- 图书馆里已经有很多书了(指向
Null
)。 - 如果我从行内单击添加另一本书,它将创建一本全新的书。但我想避免这种情况。我想从图书馆中已经存在但还不属于任何书架的书籍中进行选择。
- I have a lot of books already in the library (pointing to
Null
). - If I click 'Add another Book' from the inline it will create a totally new book. But I want to avoid that. I would like to select from the books that are already in the library but doesn't belong to any shelf yet.
推荐答案
您好,以下代码为我工作:
Hi the following code worked for me:
from widgets import ImproveRawIdFieldsForm
class BookInline(admin.TabularInline):
model = Book
raw_id_fields=('shelf',)
extra =1
class Shelf(ImproveRawIdFieldsForm):
inlines = [BookInline,]
它会创建一个管理视图,您可以在其中查看普通的书架内容以及其他内容内联这是一个原始id字段,您可以添加新的关系,并且可以使用放大镜图标从现有对象中进行选择,这会弹出所有现有书籍的列表。除了在弹出窗口中选择一本书外,您还可以在其中创建新书。因此,据我了解,这可以解决您的所有要求
It creates an admin view where you will se the normal Shelf stuff and the additional inline which is a raw id field and you have the posssibility to add new relations and you can chose from existing objects with the "magnifier" icon, which results in a pop-up of a list of all existing books. Besides chose one Book in the pop-up you can also create new Books there. So from my understanding this solves all your requirements
在此说明了针对此问题的更好解决方案:使用django admin进行一对多的内联选择
a better solution for this problem is explained here: one-to-many inline select with django admin
用例:
#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
这篇关于django-内联-搜索现有记录,而不是添加新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!