我一直在尝试在 Django 管理中显示GenericForeignKey
,但无法让它工作。我有一个可以链接到NonSupportedProgram
或SupportedProgram
类的FullCitation
类。因此,我使用了通用外键。
在管理员中,我希望用户只能从content_type
下拉列表中选择'NonSupportedProgram'
或'SupportedProgram'
,然后,从object_id
字段中,我需要用户能够从列出现有NonSuportedProgram
或现有SupportedProgram
的下拉列表中选择,并可以选择创建新。这可能吗?我哪里出错了?
models.py
class FullCitation(models.Model)
# the software to which this citation belongs
# either a supported software program or a non-supported software program
limit = models.Q(app_label = 'myprograms', model = 'supportedprogram') | models.Q(app_label = 'myprograms', model = 'nonsupportedprogram')
content_type = models.ForeignKey(ContentType), limit_choices_to = limit, )
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
is_primary = models.BooleanField(help_text="Is this the Primary Citation for the software program?")
class Meta:
unique_together = ('content_type', 'object_id')
app_label = 'myprograms'
reversion.register(FullCitation)
class NonSupportedProgram(models.Model):
title = models.CharField(max_length=256, blank = True)
full_citation = generic.GenericRelation('FullCitation')
class Meta:
app_label = 'myprograms'
reversion.register(NonSBGridProgram)
class SupportedProgram(models.Model):
title = models.CharField(max_length=256, blank = True)
full_citation = generic.GenericRelation('FullCitation')
# and a bunch of other fields.....
admin.py
class FullCitationAdmin(reversion.VersionAdmin):
fieldsets = (
('Which Program', {
'fields': ('content_type', 'object_id', ),
}),
('Citation Information', {
'fields': ('is_primary',),
}),)
# autocomplete_lookup_fields = {
# 'generic': [['content_type', 'object_id']],
# }
# inlines = ['NonSupportedProgramInline', ]
list_display = ('content_object', 'is_primary',)
search_fields = ('content_object__title', )
# list_filter = ('content_object',)
这是一个在 Django Admin 中渲染 GenericForeignKeys 的模块:
https://github.com/lexich/genericrelationview
它只是不适用于没有冲突的jQuery设置(如来自Django CMS的设置(。