我目前正尝试在django-filters的帮助下创建过滤器。每当我尝试对另一个模型的特定属性的外键进行过滤时,这些过滤器将显示为:
代替该对象的实际属性。
在最好的情况下,我希望能够为某些多选选项分别定义键和标签。键应以url参数结尾,而标签应以表格形式显示。
代码如下:
models.py
class Content(models.Model):
content_id = models.AutoField(primary_key=True)
content_parent_id = models.IntegerField(blank=True, null=True)
content_media = models.ForeignKey('Media', models.DO_NOTHING)
content_date_fetched = models.DateTimeField(blank=True, null=True)
content_date_created = models.DateTimeField(blank=True, null=True)
content_text = models.TextField(blank=True, null=True)
class Meta:
managed = False
db_table = 'content'
class Media(models.Model):
media_id = models.AutoField(primary_key=True)
media_type = models.CharField(max_length=50)
media_name = models.CharField(max_length=255),
class Meta:
managed = False
db_table = 'media'
filters.py
import django_filters
from .models import Content, Media, File
from django import forms
class MediaFilter(django_filters.FilterSet):
class Meta:
model = Media
fields = ['media_id', 'media_name']
class ContentFilter(django_filters.FilterSet):
content_id = django_filters.CharFilter(lookup_expr='icontains')
content_title = django_filters.CharFilter(lookup_expr='icontains')
content_text = django_filters.CharFilter(lookup_expr='icontains')
media = django_filters.ModelMultipleChoiceFilter(
field_name='content_media_id__media_name',
to_field_name='media_name', #option value
queryset=Media.objects.all(),
label = 'media_name',
widget=forms.CheckboxSelectMultiple(),
)
class Meta:
model = Content
fields = ['content_title', 'content_text', 'content_id', 'media']
在当前示例中,正如我在玩耍时,实际名称media_name
是选择项的值。我希望将它们作为每个选择项的实际名称/标签,而将id用作值。