9

I made a JSON serializer to view. I returned a QuerySet object which is called entries which looks for POST argument as below:

entries = blog.models.Entry.objects.filter(content__icontains=request.POST.get('q'))

Then I used serializers from django.core.

serializers.serialize("json", entries, fields=('title', 'content', 'created'))

This works like a charm, however, I want to return contents into truncated words.


Environment

  • Django 1.8.7
  • Python 3.4
Community
  • 1
  • 1
Eray Erdin
  • 2,633
  • 1
  • 32
  • 66

1 Answers1

17

You can use the Truncator class from django.utils.text, for example:

from django.utils.text import Truncator
my_text = "Lorem ipsum dolor sit amet"
n_words = 3
truncated_text = Truncator(my_text).words(n_words)
print(truncated_text)
# Lorem ipsum dolor...

Truncator can also truncate to a number of characters, and can parse HTML as well as plain text. While official docs appear to missing, the source code is pretty senf-explanatory, see: https://github.com/django/django/blob/master/django/utils/text.py

nik_m
  • 11,825
  • 4
  • 43
  • 57
Dave
  • 406
  • 6
  • 6