我目前正在使用 Django REST framework 3.11.0 以及 Django 3.0.6。我对 DRF 还很新,不确定如何解决这个问题。我试图将排序应用于 SerializerMethodField 和枚举。我能够找到一些文档,说明我可以自己制作 OrderFilter,但我不知道该怎么做。是否有任何示例可供参考?以下是我的代码。
视图:
模型
我似乎无法按
视图:
from rest_framework import generics
from V1.assets.models.asset_main import Asset
from V1.assets.serializers.asset_serializer import AssetSerializer
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
class AssetsView(generics.ListCreateAPIView):
queryset = Asset.objects.all()
serializer_class = AssetSerializer
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filter_fields = ['asset_type']
search_fields = ['asset_type', 'asset_properties', 'current_employee_name']
模型
class AssetType(models.TextChoices):
LAPTOP = 'LPT', _('Laptop')
MOUSE = 'MSE', _('Mouse')
MONITOR = 'MTR', _('Monitor')
AC_ADAPTER = 'ADR', _('AC Adapter')
TELEPHONE = 'TLP', _('Telephone')
LOCK = 'LCK', _('Lock')
HEADSET = 'HDS', _('Headset')
class Asset(CreatedModified):
asset_type = models.CharField(
max_length=3,
choices=AssetType.choices,
default=None
)
asset_properties = JSONField(default=dict)
current_employee = models.ForeignKey(
Employee,
related_name='assets_current_employees',
related_query_name='assets_current_employee',
default=None,
on_delete=models.CASCADE,
null=True,
blank=True
)
class Meta:
app_label = 'assets'
default_related_name = 'assets'
def __str__(self):
return self.asset_type
序列化器
from V1.general.enums import AssetStatus, AssetType
from V1.accounts.models.employee_main import Employee
class AssetSerializer(serializers.ModelSerializer):
current_employee_name = serializers.SerializerMethodField('get_full_name_from_employee')
asset_type = serializers.CharField(source='get_asset_type_display')
class Meta:
model = Asset
fields = (
'id',
'asset_type',
'asset_properties',
'current_employee',
'current_employee_name'
)
extra_kwargs = {
'asset_type': {
'required': True,
'allow_blank': False
}
}
def get_full_name_from_employee(self, asset):
current_employee_name = asset.current_employee.first_name + ' ' + asset.current_employee.last_name
return current_employee_name
我似乎无法按
current_employee_name
或 asset_type
排序。我应该怎么做才能允许对这两个字段进行排序?