Advertisement
horozov86

Notes

Dec 10th, 2023 (edited)
595
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.87 KB | None | 0 0
  1. CUSTOM MANAGER
  2.  
  3. class AuthorManager(models.Manager):
  4.     def get_authors_by_article_count(self):
  5.         return self.annotate(
  6.             num_articles=models.Count('articles')
  7.         ).order_by(
  8.             '-num_articles', 'email'
  9.         )
  10.  
  11. QUERIES 1.1 Q
  12.  
  13. from main_app.models import Author, Article, Review
  14. from django.db.models import Q
  15.  
  16.  
  17. def get_authors(search_name=None, search_email=None):
  18.     if search_name is None and search_email is None:
  19.         return ""
  20.  
  21.     query_name = Q(full_name__icontains=search_name)
  22.     query_email = Q(email__icontains=search_email)
  23.  
  24.     if search_name and search_email:
  25.         query = query_name & query_email
  26.     elif search_name:
  27.         query = query_name
  28.     else:
  29.         query = query_email
  30.  
  31.     authors = Author.objects.filter(query).order_by('-full_name')
  32.  
  33.     if not authors:
  34.         return ""
  35.  
  36.     result = []
  37.  
  38.     for author in authors:
  39.         result.append(f"Author: {author.full_name}, email: {author.email}, status: {'Banned' if author.is_banned else 'Not Banned'}")
  40.  
  41.     return "\n".join(result)
  42.  
  43. QUERIES 1.2 AND 1.3
  44.  
  45. def get_top_publisher():
  46.     top_publisher = Author.objects.annotate(
  47.         num_articles=Count("articles")
  48.     ).order_by(
  49.         '-num_articles', 'email'
  50.     ).first()
  51.  
  52.     if top_publisher is None or top_publisher.num_articles == 0:
  53.         return ""
  54.  
  55.     return f"Top Author: {top_publisher.full_name} with {top_publisher.num_articles} published articles."
  56.  
  57.  
  58. def get_top_reviewer():
  59.     top_reviewer = Author.objects.annotate(
  60.         num_reviews=Count('reviews')
  61.     ).order_by(
  62.         '-num_reviews', 'email'
  63.     ).first()
  64.  
  65.     if top_reviewer is None or top_reviewer.num_reviews == 0:
  66.         return ''
  67.  
  68.     return f"Top Reviewer: {top_reviewer.full_name} with {top_reviewer.num_reviews} published reviews."
  69.  
  70. QUERIES 2.1
  71.  
  72. def get_latest_article():
  73.     latest_article = Article.objects.prefetch_related('authors', 'reviews').order_by('-published_on').first()
  74.  
  75.     if latest_article is None:
  76.         return ''
  77.  
  78.     author_names = ', '.join(author.full_name for author in latest_article.authors.all().order_by('full_name'))
  79.     num_reviews = latest_article.reviews.count()
  80.     avg_rating = sum([r.rating for r in latest_article.reviews.all()]) / num_reviews if num_reviews else 0.0
  81.  
  82.     return (f"The latest article is: {latest_article.title}."
  83.             f" Authors: {author_names}. Reviewed: {num_reviews} times."
  84.             f" Average Rating: {avg_rating:.2f}.")
  85.  
  86. QUERIES 2.2
  87.  
  88. def get_top_rated_article():
  89.     top_article = Article.objects.annotate(
  90.         average_rating=Avg('reviews__rating') # СРЕДИЯ РЕЙТИНГ НА ВСЯКА ЕДНА СТАРИЯ
  91.     ).order_by(
  92.         '-average_rating', 'title' # СОРТИРАМЕ В НИЗХОДЯЩ РЕД ПО СРЕДЕН РЕЙТИНГ И ЗАГЛАВИЕ НА СТАТИЯТА
  93.     ).first() # ВЗИМАМЕ ПЪРВАТА СТАТИЯ, Т.Е ТАЗИ С НАЙ-ВИСОК СРЕДЕН РЕЙТИНГ
  94.  
  95.     num_reviews = top_article.reviews.count()
  96.  
  97.     if top_article is None or num_reviews == 0:
  98.         return ''
  99.     avg_rating = top_article.average_rating
  100.  
  101.     return (f"The top-rated article is: {top_article.title},"
  102.             f" with an average rating of {avg_rating:.2f},"
  103.             f" reviewed {num_reviews} times.")
  104.  
  105. QUERIES 2.3
  106.  
  107. def ban_author(email=None):
  108.     author_banned = Author.objects.prefetch_related('reviews').filter(email__exact=email).first() # използваме
  109.     # prefetch_related защото по надолу ни трябва reviews
  110.  
  111.     if author_banned is None or email is None:
  112.         return "No authors banned."
  113.  
  114.     num_reviews = author_banned.reviews.count()
  115.  
  116.     author_banned.is_banned = True
  117.     author_banned.save()
  118.     author_banned.reviews.all().delete()
  119.  
  120.     return f"Author: {author_banned.full_name} is banned! {num_reviews} reviews deleted."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement