给定以下 Django 模型,如何使用 django_property_filter 包过滤模型的属性:
# models.py
from django.db import models
class Manager(models.Model):
name = models.CharField(max_length=35)
class Plan(models.Model):
name = models.CharField(max_length=35)
manager = models.ForeignKey(Manager, on_delete=models.CASCADE)
class Member:
name = models.CharField(max_length=35)
plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
@property
def manager(self):
return self.plan.manager
# filters.py
from django_property_filter import PropertyFilterSet
class Meta:
model = Member
fields = []
class MemberFilter(PropertyFilterSet):
manager = ???(
field_name='manager',
)
我尝试了 PropertyMultipleChoiceFilter 和 PropertyChoiceFilter 但没有成功。 Manager.objects.all() 中的 m 选择设置为 [(m.pk, m.name)]。
要使用 django_property_filter 过滤模型的属性,您需要使用 PropertyModelChoiceFilter 或 PropertyModelMultipleChoiceFilter,它们接受查询集作为选择参数。例如,您可以写:
from django_property_filter import PropertyFilterSet, PropertyModelChoiceFilter
class MemberFilter(PropertyFilterSet):
manager = PropertyModelChoiceFilter(
field_name='manager',
queryset=Manager.objects.all(),
to_field_name='name',
)
class Meta:
model = Member
fields = []