通过内联显示在Django Admin中编辑/添加外键对象 [英] Editing/Adding a Foreign Key object through inline display in the Django Admin
问题描述
我的Complete_Book模型具有Book的外键。 Book是我从已安装的应用程序(即外部应用程序)中使用的东西,我希望能够直接从Complete_Book管理员编辑/创建 Book。这可能吗?我无法使用内联,因为我的外键关系是内联所允许的后退。
My Complete_Book model has a foreign key to Book. Book is something I'm using from an installed app (so, an 'outside app') I would like to be able to edit/create a 'Book' directly from the Complete_Book admin. Is this possible? I haven't been able to use inlines, as my foreign key relationship is 'backwards' from what inline allows.
我的问题与该问题中的解释相同( but-foreign-key-has-opposite-relation> Django内联显示,但是外键具有相反的关系),但我无法按照该答案中的建议重构模型。还有其他办法吗?谢谢您的帮助!
My problem is the same as that explained in this question (Django admin inline display but foreign key has opposite relation) but I cannot refactor my models as suggested in that answer. Is there any other way? Thank you for your help!
models.py
models.py
class Complete_Book(models.Model):
topic = models.ForeignKey('topic')
book = models.ForeignKey(Book)
is_primary = models.BooleanField()
subprogram_name = models.CharField(max_length = 256, blank=True)
class Book(models.Model):
title = models.CharField(max_length=512)
authors = models.CharField(max_length=2048)
year = models.PositiveIntegerField(max_length=4)
推荐答案
django_reverse_admin 是django模块,用于解决需要内联的问题,其中关系是错误的方向。
django_reverse_admin is a django module to solve this problem of needing inlines where the relationships are the 'wrong' direction.
您需要将其添加到requirements.txt中,然后将其导入:
You'll need to add it to your requirements.txt and then import it:
admin.py
from django_reverse_admin import ReverseModelAdmin
class Complete_Book(ReverseModelAdmin):
# usual admin stuff goes here
inline_type = 'tabular' # or could be 'stacked'
inline_reverse = ['book'] # could do [('book', {'fields': ['title', 'authors'})] if you only wanted to show certain fields in the create admin
admin.site.register(Book, Complete_Book)
这篇关于通过内联显示在Django Admin中编辑/添加外键对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!