排序组件OrderingFilter
models.py 文件
from django.db import models
class BaseModel(models.Model):
is_delete = models.BooleanField(default=False)
create_time = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class Car(BaseModel):
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
brand = models.ForeignKey('Brand', db_constraint=False, on_delete=models.DO_NOTHING, related_name='cars')
@property
def brand_name(self):
return self.brand.name
class Meta:
db_table = 'old_boy_car'
verbose_name = '汽车'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Brand(BaseModel):
name = models.CharField(max_length=32)
class Meta:
db_table = 'old_boy_brand'
verbose_name = '品牌'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
serializer.py文件
from rest_framework.serializers import ModelSerializer
from . import models
class CarModelSerializer(ModelSerializer):
class Meta:
model = models.Car
fields = ('name','price','brand','brand_name')
extra_kwargs = {
"brand":{
'write_only':True
},
'brand_name':{
'read_only':True
},
}
views.py 文件
from rest_framework.viewsets import ModelViewSet
from . import models, serializer
from rest_framework.filters import OrderingFilter
class CarModelViewSet(ModelViewSet):
queryset = models.Car.objects.filter(is_delete=False)
serializer_class = serializer.CarModelSerializer
filter_backends = [OrderingFilter]
# ordering_fields = ['pk','-price']
# ordering_fields = '__all__'
总结
# 如果有ordering_fields
# url输入的是该字段,就按该字段排序(ordering_fields必须是可以参与order_by()的字段,否则会报错)否则不排序
# 如果ordering_fields = '__all__':
# 1. 如 url:/ordering = -sdfsfd,则 ordering = None,不排序
# 2. 如 url:/ordering = -price, 则 ordering = -price,按-price排序
# 如果没有指定ordering_fields,
# 1. 不参与序列化,如:sdsadf。则 ordering = None,不排序
# 2. 参与序列化且是表字段,如:price,则 ordering = price, 按price排序,
# 3. 参与序列化不是表字段,如:brand_name, 则 ordering = brand_name,报错(order_by(brand_name)出错)