Advertisement
Fahim_7861

database models query django

Sep 25th, 2021
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. # ***(1)Returns all customers from customer table
  2. from accounts import models
  3. from accounts.models import Customer, Product, Order
  4.  
  5. customers = Customer.objects.all()
  6.  
  7. # (2)Returns first customer in table
  8. firstCustomer = Customer.objects.first()
  9.  
  10. # (3)Returns last customer in table
  11. lastCustomer = Customer.objects.last()
  12.  
  13. # (4)Returns single customer by name
  14. customerByName = Customer.objects.get(name='Peter Piper')
  15.  
  16. # ***(5)Returns single customer by name
  17. customerById = Customer.objects.get(id=4)
  18.  
  19. # ***(6)Returns all orders related to customer (firstCustomer variable set above)
  20. firstCustomer.order_set.all()
  21.  
  22. # (7)***Returns orders customer name: (Query parent model values)
  23. order = Order.objects.first()
  24. parentName = order.customer.name
  25.  
  26. # (8)***Returns products from products table with value of "Out Door" in category attribute
  27. products = Product.objects.filter(category="Out Door")
  28.  
  29. # (9)***Order/Sort Objects by id
  30. leastToGreatest = Product.objects.all().order_by('id')
  31. greatestToLeast = Product.objects.all().order_by('-id')
  32.  
  33. # (10) Returns all products with tag of "Sports": (Query Many to Many Fields)
  34. productsFiltered = Product.objects.filter(tags__name="Sports")
  35.  
  36. '''
  37. (11)Bonus
  38. Q: If the customer has more than 1 ball, how would you reflect it in the database?
  39. A: Because there are many different products and this value changes constantly you would most
  40. likly not want to store the value in the database but rather just make this a function we can run
  41. each time we load the customers profile
  42. '''
  43.  
  44. # Returns the total count for number of time a "Ball" was ordered by the first customer
  45. ballOrders = firstCustomer.order_set.filter(product__name="Ball").count()
  46.  
  47. # Returns total count for each product orderd
  48. allOrders = {}
  49.  
  50. for order in firstCustomer.order_set.all():
  51. if order.product.name in allOrders:
  52. allOrders[order.product.name] += 1
  53. else:
  54. allOrders[order.product.name] = 1
  55.  
  56.  
  57. # Returns: allOrders: {'Ball': 2, 'BBQ Grill': 1}
  58.  
  59.  
  60. # RELATED SET EXAMPLE
  61. class ParentModel(models.Model):
  62. name = models.CharField(max_length=200, null=True)
  63.  
  64.  
  65. class ChildModel(models.Model):
  66. parent = models.ForeignKey(Customer)
  67. name = models.CharField(max_length=200, null=True)
  68.  
  69.  
  70. parent = ParentModel.objects.first()
  71. # Returns all child models related to parent
  72. parent.childmodel_set.all()
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement