如何从StringField中剪裁/带领Whitespaces以获取Django/MongoDB中的列表视图?
想要按名称对数据进行排序,但不幸的是,有许多带有领先空间的数据,这就是为什么REST_FRAMEWORK.FILTERS.FILTERS.orderingFilter
无法正常工作的原因。 Mongo,DRF在我的项目中使用。
我的模型:
from mongoengine import DynamicDocument, fields
class Book(DynamicDocument):
name = fields.StringField(required=True)
description = fields.StringField(blank=True, null=True)
meta = {
'collection': 'books',
'strict': False,
}
我的观点:
from rest_framework.filters import OrderingFilter
from rest_framework_mongoengine import viewsets
from core.serializers import BookSerializer
from core.models import Book
class BookViewSet(viewsets.ModelViewSet):
serializer_class = BookSerializer
queryset = Book.objects.all()
filter_backends = [OrderingFilter]
ordering_fields = ['name']
ordering = ['name']
有人有任何想法,如何解决?
Want to sort data by names, but unfortunately there are many data with leading whitespaces, that is why rest_framework.filters.OrderingFilter
doesn't work properly. Mongo, DRF are used in my project.
My model:
from mongoengine import DynamicDocument, fields
class Book(DynamicDocument):
name = fields.StringField(required=True)
description = fields.StringField(blank=True, null=True)
meta = {
'collection': 'books',
'strict': False,
}
My view:
from rest_framework.filters import OrderingFilter
from rest_framework_mongoengine import viewsets
from core.serializers import BookSerializer
from core.models import Book
class BookViewSet(viewsets.ModelViewSet):
serializer_class = BookSerializer
queryset = Book.objects.all()
filter_backends = [OrderingFilter]
ordering_fields = ['name']
ordering = ['name']
Someone has any idea, how to solve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有汇总操作称为 $ trim 可以用来消毒字符串数据,如果仅要删除前导空间,则可以使用 $ ltrim ...
There is aggregation operation called $trim in mongoDB that you can use to sanitize the string data , if you want to remove only the leading spaces then you can use the $ltrim ...
如果有人处理
mongoEngine
,则可以使用querySet.aggregate()
:hester
python'trim_lower_name':{'$ ltrim':{'input ':{'$ tolower':'$ name'}}}}
,因为需要对案例不敏感的排序。If someone deals with
mongoengine
, you can solve this problem withqueryset.aggregate()
:Used
python 'trim_lower_name': {'$ltrim': {'input': {'$toLower': '$name'}}}
because need case-insensitive sorting.还为此问题找到了一个决定,
utils.py:
in views.py:
Also find one more decision for this question
utils.py:
In views.py: