gpt4 book ai didi

django - Django Admin 中的通用外键

转载 作者:行者123 更新时间:2023-12-04 18:04:56 25 4
gpt4 key购买 nike

是否可以通过 GenericForeignKey 过滤Django 管理中的对象标题?

我想按程序名称过滤,要么NonSupportedProgram.titleSupportedProgram.title ( list_filter = (SOME FIELD HERE) ),但不知道怎么做?

模型.py

class FullCitation(models.Model):
# the software to which this citation belongs
# either a supported software program or a non-supported software program
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')

class NonSupportedProgram(models.Model):
title = models.CharField(max_length=256, blank = True)
full_citation = generic.GenericRelation('FullCitation')

class SupportedProgram(models.Model):
title = models.CharField(max_length=256, blank = True)
full_citation = generic.GenericRelation('FullCitation')

最佳答案

也许您可以使用 SimpleListFilter 并定义自己的查询集,以便获得自己的结果。

更多信息在这里:
https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter

class YourCustomListFilter(admin.SimpleListFilter):
title = 'By Program Name'
parameter_name = 'program'

def lookups(self, request, model_admin):
return(
('supported','Supported Programs'),
('nonsupported', 'Non-Supported Programs')
)

def queryset(self, request, queryset):
if self.value() == 'supported':
return queryset.filter(supported__isnull=False)
if self.value() == 'nonsupported':
return queryset.filter(nonsupported__isnull=False)

admin.py
list_filter = (YourCustomListFilter,)

您需要在 GenericRelation 声明中添加 related_query_name='supported' 和 related_query_name='nonsupported' 以允许从相关对象进行查询。

有关在此处查询 GenericRelations 的更多信息:
https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#reverse-generic-relations

这应该是对正确方向的一点插入。

关于django - Django Admin 中的通用外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28655346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com