【发布时间】:2021-05-14 06:51:38
【问题描述】:
是否可以在 Django admin 中过滤相关值?我有多对多关系设置为内联显示。 但是有很多值,所以我希望能够以某种方式搜索/过滤我需要的值。
所以这里有两个模型(我用的是 Join 表):
# Create your models here.
class Country(models.Model):
name = models.CharField(max_length=100, unique=True, verbose_name='Country')
class Meta:
verbose_name_plural = "Countries"
def __str__(self):
return self.name
class OpenDestination(models.Model):
name = models.CharField(max_length=100, unique=True, verbose_name='Country')
origin_country = models.ManyToManyField(Country, through='BorderStatus')
def __str__(self):
return self.name
class BorderStatus(models.Model):
STATUS_CHOICES = [
('OP', 'OPEN'),
('SEMI', 'CAUTION'),
('CLOSED', 'CLOSED')
]
Country = models.ForeignKey(Country, on_delete=models.CASCADE)
OpenDestination = models.ForeignKey(OpenDestination, on_delete=models.CASCADE)
status = models.CharField(max_length=6, choices=STATUS_CHOICES, default='CLOSED')
class Meta:
unique_together = (('Country', 'OpenDestination'))
def __str__(self):
return str(self.Country) + ' and ' + str(self.OpenDestination)
在admin.py
class OpenDestinationInline(admin.TabularInline):
model = OpenDestination.origin_country.through
class ConutryAdmin(admin.ModelAdmin):
inlines = [
OpenDestinationInline
]
filter_horizontal = ('origin_country',)
admin.site.register(Country, ConutryAdmin)
admin.site.register(OpenDestination)
admin.site.register(BorderStatus)
所以现在当我从Country 模型访问一个国家时,我会看到来自OpenDestination 模型的许多国家的列表(由于加入表,每个国家都有自己的状态)。现在我试图弄清楚从“国家”访问单个国家时是否可以从“OpenDestination”中过滤国家。
我尝试将 filter_vertical/horizontal filter_vertical = ('name',) 添加到 CountryAdmin 但出现错误:
The value of 'filter_vertical[0]' must be a many-to-many field.
【问题讨论】:
-
我认为autocomplete fields 更适合解决这个问题。
-
当我将 filter_vertical 更改为 autocomplete_fields 时出现同样的错误
标签: django django-models django-rest-framework