Merge branch 'feature/will-also-like-news' into 'develop'

Feature/will also like news

See merge request gm/gm-backend!34
This commit is contained in:
d.kuzmenko 2019-09-30 07:58:49 +00:00
commit b724e2eeb9
2 changed files with 20 additions and 0 deletions

View File

@ -5,6 +5,7 @@ from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from rest_framework.reverse import reverse
from utils.models import BaseAttributes, TJSONField, TranslatedFieldsMixin
from random import sample as random_sample
class NewsType(models.Model):
@ -138,3 +139,21 @@ class News(BaseAttributes, TranslatedFieldsMixin):
@property
def web_url(self):
return reverse('web:news:rud', kwargs={'slug': self.slug})
@property
def list_also_like_news(self):
# without "distinct" method the doubles are arising
like_news = News.objects.published().filter(news_type=self.news_type, tags__in=models.F("tags"))\
.exclude(id=self.id).distinct()
news_count = like_news.count()
if news_count >= 6:
random_ids = random_sample(range(news_count), 6)
else:
random_ids = random_sample(range(news_count), news_count)
news_list = [{"id": like_news[r].id, "slug": like_news[r].slug} for r in random_ids]
return news_list

View File

@ -67,6 +67,7 @@ class NewsDetailSerializer(NewsBaseSerializer):
'state_display',
'author',
'country',
'list_also_like_news',
)