我有点困惑,需要一些建议如何正确组织视图。在我的Django REST Framework项目中,我有非常简单的模型和序列化器。
models.py :
class Article(models.Model):
body = models.TextField()
serializers.py :
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('id', 'body')
让我们说我的数据库中有下一个数据:
ID | BODY
-------------------------------------------------------------
1 | Aki doing his homework about japanese robot in library.
2 | All chapters are accompanied by necessary links.
3 | Japanese robot Aki doing a lot of tasks.
现在,我尝试通过JSON
请求将POST
发送到ArticleFilterView
控制器:
curl -X POST -H "Content-Type: application/json" -d '[
{
"first": ["Aki", "robot"],
"second": ["doing", "library"]
}]'
http://localhost:8000/api/article/filter/
如果任何文章的正文字段中包含单词“ Aki”和“ robot”,我想将该文章添加到JSON响应中。同时,我需要从文本中删除“正在做”和“图书馆”一词。
输入:
[{
"fisrt": ["Aki", "robot"],
"second": ["doing", "library"]
}]
输出:
[
{"id": 1, "body": "Aki his homework about japanese robot in ."},
{"id": 3, "body": "Japanese robot Aki a lot of tasks."},
]
views.py:
class ArticleFilterView(APIView):
parser_classes = (JSONParser,)
def post(self, request, format=None):
# some code
return Response({'received data': request.data})
settings.py:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
}
urls.py:(在settings.py
文件所在的目录中)
urlpatterns = [
path('api/', include('article.urls')),
]
article / urls.py:
urlpatterns = [
path(
'article/filter/',
ArticleFilterView.as_view(),
name='article_filter',
),
]
答案 0 :(得分:1)
我认为,这会起作用。 (我只提到逻辑,而不是确切的代码)
class ArticleFilterView(APIView):
parser_classes = (JSONParser,)
def post(self, request, format=None):
# some code
return_data = {}
if first got a match:
return_data.update({'received data': request.data[0]['first']})
elif second got a match:
return_data.update({'received data': request.data[0]['second']})
return_data.update({"search_result":your_serch_result})
return Response(data=return_data)
更新
完全实现view
from django.db.models import Q
class ArticleFilterView(APIView):
parser_classes = (JSONParser,)
def post(self, request, format=None):
for key, value in request.data.items():
my_filter = Q()
for search in value:
my_filter &= Q(body__icontains=search)
queryset = Article.objects.filter(my_filter)
if queryset.exists():
serializer = ArticleSerializer(queryset, many=True)
return_data = {
"search_result": serializer.data,
"input_data": {key: value}
}
return Response(data=return_data)
return Response({"message": "No data found"})
但是,您的输入有效载荷必须是dict
类似对象,
{
"first": ["Aki", "robot"],
"second": ["doing", "library"]
}
UPDATE-2
将views.py
更改为
from django.db.models import Q
class ArticleFilterView(APIView):
parser_classes = (JSONParser,)
def post(self, request, format=None):
my_filter = Q()
for search in request.data.get('first'):
my_filter &= Q(body__icontains=search)
queryset = Article.objects.filter(my_filter)
if queryset.exists():
serializer = ArticleSerializer(queryset, many=True,context={"request":request})
return_data = {
"search_result": serializer.data,
"input_data": {"first": request.data.get('first')}
}
return Response(data=return_data)
return Response({"message": "No data found"})
和序列化器为,
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('id', 'body')
def to_representation(self, instance):
data = super().to_representation(instance)
for input in self.context['request'].data.get('second'):
data['body'] = data['body'].replace(input, "")
return data