M
M
Maxim Zubenko2018-12-13 08:20:22
Django
Maxim Zubenko, 2018-12-13 08:20:22

How in Django to add to the selection results the number of occurrences of a line of text in one of the fields?

The crux of the matter is this. Let's say we have a news model:

class News(models.Model):
    category = models.CharField(max_length=15, choices=CATEGORY_NEWS_CHOISES, default='function', verbose_name='Категория')
    created = models.DateTimeField(default=get_now, verbose_name="Дата")
    brief = models.CharField(max_length=255, verbose_name='Краткая запись')
    text = models.TextField(blank=True, verbose_name='Большая новость')

And here in the view there is a simple request: Task 1 . Find out the number of images in the post text and add this number to each item in the selection. Those. you need something like:
all_news = News.objects.all().order_by('-created')

all_news.annotate(qty_img=Count(News -> text -> "в тексте найти <img src") 
# это не рабочий пример, я показываю принцип

Task 2 . Find out if a video is inserted in the text of the recording (the answer is only True or False).
Those. you need something like:
all_news.annotate(video_in_text = True if (News -> text -> "в тексте найдено class='note-video-clip' ") else False 
# это не рабочий пример, я показываю принцип

Well, it seems to be a simple task and understandable. And how to s-annotate it correctly so that it works I can’t understand.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question