gpt4 book ai didi

django - 如何在不公开数据库中字段名称的情况下使用 OrderingFilter

转载 作者:行者123 更新时间:2023-12-04 13:31:25 29 4
gpt4 key购买 nike

我有一个使用 OrderingFilter 的模型后端。现在只能按字段订购 id被允许。

我也想提供按其他字段排序的选项,但不必在我的数据库中公开字段名称。有没有办法做到这一点?

最佳答案

我创建了一个 AliasedOrderingFilter 应该很好地满足这个需求。它扩展了 ordering_fields 属性以允许字段和字符串的元组。例如,您可以将 View ordering_fields 设置为:

ordering_fields = (('alias1', 'field1'),('alias2', 'field2'), 'field3')

在带有 ordering=alias1,-alias2,field3 的请求中使用此类将导致:
qs.order_by('field1', '-field2', 'field3)

类(class):
class AliasedOrderingFilter(OrderingFilter):
''' this allows us to "alias" fields on our model to ensure consistency at the API level
We do so by allowing the ordering_fields attribute to accept a list of tuples.
You can mix and match, i.e.:
ordering_fields = (('alias1', 'field1'), 'field2', ('alias2', 'field2')) '''

def remove_invalid_fields(self, queryset, fields, view):
valid_fields = getattr(view, 'ordering_fields', self.ordering_fields)
if valid_fields is None or valid_fields == '__all__':
return super(AliasedOrderingFilter, self).remove_invalid_fields(queryset, fields, view)

aliased_fields = {}
for field in valid_fields:
if isinstance(field, basestring):
aliased_fields[field] = field
else:
aliased_fields[field[0]] = field[1]

ordering = []
for raw_field in fields:
invert = raw_field[0] == '-'
field = raw_field.lstrip('-')
if field in aliased_fields:
if invert:
ordering.append('-{}'.format(aliased_fields[field]))
else:
ordering.append(aliased_fields[field])
return ordering

关于django - 如何在不公开数据库中字段名称的情况下使用 OrderingFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33691933/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com