Advertisement
horozov86

Advanced Queries Exercise

Dec 7th, 2023 (edited)
651
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. # 1.    Real Estate Listing
  2.  
  3. class RealEstateListingManager(models.Manager):
  4.     def by_property_type(self, property_type: str):
  5.         return self.filter(property_type=property_type)
  6.        
  7.        
  8.    
  9.     def in_price_range(self, min_price: Decimal, max_price: Decimal):
  10.         return self.filter(price__range(min_price, max_price))
  11.        
  12.        
  13.     def with_bedrooms(self, bedrooms_count: int):
  14.         return self.filter(bedrooms=bedrooms_count)
  15.        
  16.    
  17.     def popular_locations(self):
  18.         return self.values("loaction").annotate(bedrooms_count=Coout('loaction')).order_by("-loaction_count", "id")[:2]
  19.  
  20.  
  21. # 2.    Video Games Library
  22.  
  23.  
  24. class VideoGameManager(models.Manager):
  25.     def games_by_genre(self, genre: str):
  26.         return self.filter(genre=genre)
  27.        
  28.     def recently_released_games(self, year: int):
  29.         return self.filter(release_year__gte=year)
  30.        
  31.        
  32.     def highest_rated_game(self):
  33.         return self.annotate(max_rating=Max('rating')).order_by('-max_rating').first()
  34.        
  35.     def lowest_rated_game(self):
  36.         return self.annotate(min_rating=Min('rating')).order_by('max_rating').first()
  37.        
  38.     def average_rating(self):
  39.         average_rating = self.aggregate(average_rating=Avg('rating'))["average_rating"]
  40.         return f"{average_rating:.1f}"
  41.  
  42.  
  43. 4IT Sector
  44.  
  45. class Technology(models.Model):
  46.     name = models.CharField(max_length=100)
  47.     description = models.TextField()
  48.  
  49.  
  50. class Project(models.Model):
  51.     name = models.CharField(max_length=100)
  52.     description = models.TextField()
  53.     technologies_used = models.ManyToManyField(Technology, related_name='projects')
  54.    
  55.     def get_programmers_with_technologies(self):
  56.         return self.programmers.prefetch_related(projects__technologies_used)
  57.  
  58.  
  59. class Programmer(models.Model):
  60.     name = models.CharField(max_length=100)
  61.     projects = models.ManyToManyField(Project, related_name='programmers')
  62.    
  63.     def get_projects_with_technologies(self):
  64.         return self.projects.prefetch_related(technologies_used)
  65.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement