Search code examples
pythonjsondjangoserializationtruncate

Is There A Way to Truncate by Words in View in Django?


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

Solution

  • 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