decided to make API on DRF in his free time. For learning purposes.
API will be similar from the online menu.
When creating models, a question appeared how to properly calculate the total number of identical products. Test one client can admit can buy 5 burgers, and when adding them to the basket, I want to implement the product name + number + total price.
If you know suitable literature, also a good option.
(not common on the database, but by aggregating in Django ORM)
For greater understanding, current models look like this:
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model
Class Category:
Name = Models.charfield ('name category', max_length = 200, unique = true)
Slug = Models.Slugfield ()
Description = Models.TextField ('Description category')
Class Meta:
Ordering = ['Name']
DEF __STR __ (SELF):
Return Self.name.
Class Product:
Name = Models.charfield ('product name', max_length = 100, unique = true)
Description = Models.TextField ('Product Description', Blank = True, NULL = TRUE)
Category = Models.ForeignKey (
Category,
ON_DELETE = MODELS.SET_NULL,
related_name = 'Category'
)
Price = Models.decimalfield (decimal_places = 2)
Class Meta:
Ordering = ['Name']
DEF __STR __ (SELF):
Return Self.name.
Class Basket (Models.Model):
User = Models.ForeignKey (
User, On_delete = Models.Cascade, Related_Name = 'Allbasket'
)
Products = Models.ForeignKey (
Product, On_delete = Models.cascade, Related_Name = 'Alluser'
)
Created = Models.dateTimeField (AUTO_NOW_ADD = TRUE)
DEF __STR __ (SELF):
Return F '{Self.user} {self.products}'
Thank you in advance!
Answer 1
You can create Property
method>Basket Basket
for counting the consoles of goods in the basket:
class basket (models.model):
...
@Property.
DEF Get_Quantity ():
Return Self.Products.all (). Count ()
You can call this method like this:
basket = basket.objects.all ()
For Item in Basket:
item.get_quantity ()