Django Admin 搜索字段反向查找
Django Admin Search field reverse lookup
我有以下型号:
class Policy(models.Model):
name = models.CharField(max_length=40)
def __str__(self) -> str:
return self.name
class Meta:
verbose_name_plural = 'Policies'
class Statement(models.Model):
name = models.CharField(max_length=40)
policy = models.ForeignKey(
to=Policy,
on_delete=models.CASCADE,
related_name='statements'
)
action = models.CharField(max_length=64)
resource = models.CharField(max_length=128)
和以下简单模型管理员:
class PolicyAdmin(admin.ModelAdmin):
inlines = [StatementInline]
search_fields = [name,]
class Meta:
model = Policy
我想实现的是在策略更改列表上启用搜索功能,通过它除了策略名称之外,我还可以使用声明模型的名称字段搜索策略。
@admin.register(Policy)
class ExapmleAdmin(admin.ModelAdmin):
search_fields = ("statements__name",)
class Meta:
model = Policy
admin.site.register(Statement)
在您的 admin.py 文件上。可以这样用Statement模型的name字段搜索Policy
我有以下型号:
class Policy(models.Model):
name = models.CharField(max_length=40)
def __str__(self) -> str:
return self.name
class Meta:
verbose_name_plural = 'Policies'
class Statement(models.Model):
name = models.CharField(max_length=40)
policy = models.ForeignKey(
to=Policy,
on_delete=models.CASCADE,
related_name='statements'
)
action = models.CharField(max_length=64)
resource = models.CharField(max_length=128)
和以下简单模型管理员:
class PolicyAdmin(admin.ModelAdmin):
inlines = [StatementInline]
search_fields = [name,]
class Meta:
model = Policy
我想实现的是在策略更改列表上启用搜索功能,通过它除了策略名称之外,我还可以使用声明模型的名称字段搜索策略。
@admin.register(Policy)
class ExapmleAdmin(admin.ModelAdmin):
search_fields = ("statements__name",)
class Meta:
model = Policy
admin.site.register(Statement)
在您的 admin.py 文件上。可以这样用Statement模型的name字段搜索Policy