我ViewSet
SearchFilter
filter_backends
中有{
[{
"username": "jonh";
},
{
"fullname": "Jonh";
},
{
"username": "jo";
},
{
"fullname": "Johnson";
}
]
}
和两个search_fields。如何返回JSON代表唯一的字段结果?
例如,如果我使用" jo"发送搜索响应。 substring我只有一个字段用于此搜索(资助的用户名或全名),而不是每个JSON对象中的用户名和电子邮件:
class UserViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
filter_backends = (filters.SearchFilter,)
search_fields = ('^username', '^fullname',)
def get_serializer_class(self):
if hasattr(self, 'action') and self.action == 'list':
return UserListSerializer
return UserDetailSerializer
viewsets.py:
class UserListSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'fullname')
serializers.py:
public async Task InsertEdgesByName(List<string> nodeListA, List<string> nodeListB,
List<int> weightList, string type)
{
for (var i = 0; i < nodeListA.Count; i += 200)
{
using (var sw = new StreamWriter(File.OpenWrite($"tempEdge-{type}.csv")))
{
sw.Write("From,To,Weight\n");
for (var j = i;
j < i + 200 &
j < nodeListA.Count;
j++)
{
sw.Write($"{nodeListA[j]}," +
$"{nodeListB[j]}," +
$"{weightList[j]} + id:{j}" +
$"\n");
}
}
var f = new FileInfo($"tempEdge-{type}.csv");
await Client.Cypher
.LoadCsv(new Uri("file://" + f.FullName), "rels", true)
.Match("(from {label: rels.From}), (to {label: rels.To})")
.Create($"(from)-[:{type} {{weight: rels.Weight}}]->(to);")
.ExecuteWithoutResultsAsync();
_logger.LogDebug($"{DateTime.Now}\tEdges inserted\t\tedges inserted: {i}");
}
}
答案 0 :(得分:0)
我会创建一个Serializer工厂函数,它将搜索参数作为参数:
def generate_user_list_serializer(search_terms):
class UserListSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = tuple(search_terms)
return UserListSerializer
然后在您的视图中,让动态生成序列化程序:
def get_serializer_class(self):
# make sure that the fields are available
validated_params = [p for p in self.query_params if p in Myfields]
return generate_user_list_serializer(self.query_params)