Значения набора запросов Django, которые будут изменены и отправлены пользователю в виде простой текстовой копии - PullRequest
0 голосов
/ 30 ноября 2018

Это мой код, который может отправлять текстовый файл пользователю со всеми результатами набора запросов, но требуется выравнивание результатов путем удаления символов.

def save_search(request,q="deve"):
   filename = "mytext.txt"
   content =Buildkb.objects.values("text","knowledge","created_by_email").
               filter(Q(knowledge__icontains=q)|Q(text__icontains=q))
   response = HttpResponse(content, content_type='text/plain')
   response['Content-Disposition'] = 'attachment; filename{0}'.format(filename)
return response

вывод: -

 {'knowledge': 'Deve Category.', 'created_by_email': 'user1@gmail.com', 'text': 'Deve'}{'knowledge': 'Software development life cycle (SDLC) is a series of phases that provide a common understanding of the software building process. How the software will be realized and developed from the business understanding and requirements elicitation phase to convert these business ideas and requirements into functions and features until its usage and operation to achieve the business needs. The good software engineer should have enough knowledge on how to choose the SDLC model based on the project context and the business requirement.', 'created_by_email': 'user3@gmail.com', 'text': '1.1'}{'knowledge': 'Software development life cycle (SDLC) is a series of phases that provide a common understanding of the software building process. How the software will be realised and developed from the business understanding and requirements elicitation phase to convert these business ideas and requirements into functions and features until its usage and operation to achieve the business needs. The good software engineer should have enough knowledge on how to choose the SDLC model based on the project context and the business requirements.\n\n', 'created_by_email': 'user3@gmail.com', 'text': 'dev'}{'knowledge': ' the department develops applications http://192.168.1.200:2000/buildknowledge/', 'created_by_email': 'prakash.mutalik@gmail.com', 'text': 'development'}{'knowledge': 'Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA),meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.\n\nJava applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. As of 2016, Java is one of the most popular programming languages in use, particularly for client-server web applications, with a reported 9 million developers.Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle Corporation) and released in 1995 as a core component of Sun Microsystems\' Java platform. The language derives much of its syntax from C and C  , but it has fewer low-level facilities than either of them.', 'created_by_email': 'user3@gmail.com', 'text': 'java'}

Требование: -

knowledge: Deve Category.
created_by_email:'user1@gmail.com'
text: Deve

knowledge: Software development life cycle (SDLC) is a series of phases that 
provide a common understanding of the software building process. How the 
software will be realized and developed from the business understanding and 
requirements elicitation phase to convert these business ideas and 
requirements into functions and features until its usage and operation to 
achieve the business needs. The good software engineer should have enough 
knowledge on how to choose the SDLC model based on the project context and 
the business requirement. 
created_by_email: 'user3@gmail.com'
text: 1.1

knowledge: Software development life cycle (SDLC) is a series of phases 
that provide a common understanding of the software building process. How 
the software will be realised and developed from the business understanding 
and requirements elicitation phase to convert these business ideas and 
requirements into functions and features until its usage and operation to 
achieve the business needs. The good software engineer should have enough 
knowledge on how to choose the SDLC model based on the project context and 
the business requirements.\n\n
created_by_email: 'user3@gmail.com'
text: dev

knowledge: the department develops applications
http://192.168.1.200:2000/buildknowledge/', 
created_by_email: 'user4@gmail.com'
text: 'development'

Ответы [ 2 ]

0 голосов
/ 30 ноября 2018

Ответ Jitendra является правильным, но имейте в виду, что альтернативой является использование render () для рендеринга шаблона, который получает ваш контент в качестве контекста.

Затем вы можете выполнить форматирование в шаблоне, и это может дать вам большую гибкость при форматировании выходных данных, чтобы они хорошо выглядели на отображаемой странице.

https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/

0 голосов
/ 30 ноября 2018

В REST framework доступно несколько рендеров.Если вы хотите получить простой текстовый ответ, создайте пользовательский рендер.

from django.utils.encoding import smart_unicode
from rest_framework import renderers


class PlainTextRenderer(renderers.BaseRenderer):
    media_type = 'text/plain'
    format = 'txt'

    def render(self, data, media_type=None, renderer_context=None):
        <<Write your custom code here>>
        return data.encode(self.charset)

https://www.django -rest-framework.org / api-guide / renderers / # custom-renderers

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...