I want to get each product's total price in all orders which I mean how much each product sold in all orders. What Query should I write in views.py to display this matter in html?
this is my models.py:
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField(null=True)
description = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Shipping', 'Shipping'),
('Delivered', 'Delivered'),
)
# order will remain after customer deleted
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
note = models.CharField(max_length=200, null=True)
def __str__(self):
return self.product.name
and this is my views.py:
def home(request):
products = Product.objects.all()
orders = Order.objects.all()
total_order_prices = Order.objects.aggregate(Sum('price'))
orders.products = Product.objects.all().aggregate(Sum('price'))
context = {'orders':orders, 'products':products,'total_order_prices': total_order_prices }
return render(request, 'account/home.html', context)
Morez!
What I recommend is defining a foreign key to Order() in the Product(). Doing so would allow you to get related objects much more easily, as shown here.
All you would have to do is products = order.product_set.
Hope it helps!
Related
I am trying to display a product list page with products attributes along with category which is a MPTT field. I want to display the category assigned to that particular product in the product list page. How can i achieve this?
Models
class Category(MPTTModel):
"""
Inventory Category table implimented with MPTT
"""
name = models.CharField(
max_length=100,
null=False,
unique=False,
blank=False,
verbose_name=_("category name"),
help_text=_("format: required, max-100"),
)
slug = AutoSlugField(populate_from='name')
cat_img = models.ImageField(upload_to='images/categories/')
parent = TreeForeignKey(
"self",
on_delete=models.PROTECT,
related_name="children",
null=True,
blank=True,
unique=False,
verbose_name=_("parent of category"),
help_text=_("format: not required"),
)
class MPTTMeta:
order_insertion_by = ["name"]
class Meta:
verbose_name = _("product category")
verbose_name_plural = _("product categories")
def __str__(self):
return self.name
class Product(models.Model):
"""
Product details table
"""
product_id = models.UUIDField(default=uuid.uuid4, editable=False)
sku = models.CharField(max_length=255, blank=True, null=True)
name = models.CharField(
max_length=255,
unique=False,
null=False,
blank=False,
verbose_name=_("product name"),
help_text=_("format: required, max-255"),
)
slug = AutoSlugField(populate_from='name')
price = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
description = models.TextField(
unique=False,
null=True,
blank=True,
verbose_name=_("product description"),
help_text=_("format: required"),
)
prd_img = models.ImageField(upload_to='images/products/', null=True, blank=True)
category = TreeManyToManyField(Category, null=True, blank=True)
modifier_group = models.ManyToManyField(ModifierGroup, null=True, blank=True)
def __str__(self):
return self.name
Views
#login_required(login_url='/login/')
def productList(request):
products = Product.objects.all()
context = {'products':products}
template = 'product/product/products.html'
return render(request,template,context)
Template
<td class="text-end pe-0" data-order="37">
<span class="fw-bold ms-3">{{product.category.name}}</span>
</td>
Template Result
How can i query and display the category for that particular product in the product list page?
While creating new products I'm getting such kind of error. Can someone help me?
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
name_geo = models.CharField(max_length=200, null=True, blank=True)
image = models.ImageField(null=True, blank=True, default='/placeholder.png')
brand = models.CharField(max_length=200, null=True, blank=True)
category = models.ForeignKey(Category, null=False, default=0, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
countInStock = models.IntegerField(null=True, blank=True, default=0)
createdAt = models.DateTimeField(auto_now_add=True)
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return self.name_geo
class Category(models.Model):
_id = models.AutoField(primary_key=True, editable=False)
name = models.CharField(max_length=200, null=True, blank=True)
createdAt = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
#api_view(['POST'])
def createProduct(request):
user = request.user
product = Product.objects.create(
user=user,
name_geo="Sample Name",
category="Sample Category",
price=0,
brand='Sample Brand',
countInStock=0,
)
serializer = ProductSerializer(product, many=False)
return Response(serializer.data)
Without separating category class in models.py everything works fine. I mean If i didn't use ForeignKey in Products class for category
It just has to be a Category Instance/Object
product = Product.objects.create(
user=user,
name_geo="Sample Name",
category=Category.objects.get_or_create(name="Sample Category"),
price=0,
brand='Sample Brand',
countInStock=0,
)
Notes:
You could just do a .get() or a .filter().first() if you don't want to create
If you use a form, you can get away with just the Category's PK/_id in the POST
this type of thing: f = form(request.POST) f.is_valid() f.save()
At the end that field will hold the PK/_id/Row# of the Category Obj
I have database and I want to extract specific data of specific user from queryset. Now i have this
VIEW
def index(request):
customerByName = Customer.objects.get(name='pablo')
shopListById = ShopList.objects.get(transaction_id=1)
shpoListSpecific = customerByName.shoplist_set.all()
specificProducts = shopListById.shoplistproduct_set.all()
context = {'customerByName':customerByName, 'shpoListSpecific':shpoListSpecific, 'shopListById':shopListById,
'specificProducts': specificProducts}
return render(request, 'QuickShopperApp/home.html', context)
MODELS
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
device = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
if self.name:
name = self.name
else:
name = self.device
return str(name)
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class ShopList(models.Model): # cart
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
#product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
class ShopListProduct(models.Model): # each ShopList will have multiple ShopListProduct
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
shopList = models.ForeignKey(ShopList, on_delete=models.SET_NULL, null=True) #shoplistitem.shoplist
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.product)
template.html
<h3>specificProducts: {{specificProducts}}</h3>
On my side i see items of specific customer.
specificProducts: <QuerySet [<ShopListProduct: Apple>, <ShopListProduct: Cucumber>, <ShopListProduct: Cucumber>]>
How can i get only Apple, Cucumber, Cucumber?
try this
'specificProducts': specificProducts.values_list('product__name')
or
'specificProducts': list(specificProducts.values_list('product__name', flat=True))
https://docs.djangoproject.com/en/3.1/ref/models/querysets/#values-list
I want to query from OrderItem Model like
total_orders = OrderItem.objects.filter(product.user == request.user.id).count()
but i am getting error
**
NameError at /home
name 'product' is not defined
**
MY MODELS:
Product Model:
class Product(models.Model):
title = models.CharField(max_length=150)
user = models.ForeignKey(
User, blank=True, null=True, on_delete=models.SET_DEFAULT, default=None)
description = models.TextField()
price = models.FloatField()
quantity = models.IntegerField(default=False, null=True, blank=False)
minorder = models.CharField(
max_length=150, help_text='Minum Products that want to sell on per order', null=True, default=None, blank=True)
image = models.ImageField()
category = models.ForeignKey(
Categories, default=1, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)
def __str__(self):
return self.title
Order Item Model
class OrderItem(models.Model):
product = models.ForeignKey(
Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(
Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.FloatField(default=0, null=True, blank=True)
date_orderd = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
User, on_delete=models.SET_NULL, blank=True, null=True)
price = models.FloatField(blank=True, null=True)
def __str__(self):
return str(self.product)
My View:
def home(request):
total_orders = OrderItem.objects.filter(
product.user == request.user.id).count()
return render(request, "sellerprofile/home.html", {'total_orders': total_orders})
Do:
total_orders = OrderItem.objects.filter(product__user=request.user).count()
You can look at the documentation here about field lookups on more detail.
i am trying to build my first project, a CRM website to handle orders and inventory.
and i got stuck, i was able to link orders to customer.
but when i try to build order that contain multi items. for some reason i didn't find a way to do it.
hope you can assist me.
so I have User>>Order>>Multi Items.
questions:
1) does the best practice here is just use ForeignKey ?
this my model's code:
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
def date_createdview(self):
return self.date_created.strftime('%B %d %Y')
class Product(models.Model):
CATEGORY = (
('General', 'General'),
('SmartHome', 'SmartHome'),
('Software', 'Software'),
('Mobile', 'Mobile'),
)
name = models.CharField(verbose_name='שם', max_length=200, null=True)
price = models.FloatField(verbose_name='מחיר', null=True)
category = models.CharField(max_length=200, null=True, choices=CATEGORY, verbose_name='קטגוריה')
description = models.CharField(max_length=200, null=True, verbose_name='מלל חופשי')
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Order(models.Model):
STATUS = (
('New', 'New'),
('Work in progress', 'Work in progress'),
('completed', 'completed'),
)
customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
def date_createdview(self):
return self.date_created.strftime('%d/%m/%Y')
class OrderItem(models.Model):
product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE)
order = models.ForeignKey(Order, null=True, on_delete=models.CASCADE)
quantity = models.IntegerField(null=True)
2)how should I build my views or forms?
i want to make it dynamic, when i enter the order i can insert items and see the new item get add to a list of the items in the order.
how can save the order number and add new items?
this is my product view, it's working. I can add new products.
#login_required(login_url="login")
def products(request):
form = ProductForm(request.POST or None)
if form.is_valid():
form.save()
products = Product.objects.all()
context = {'form': form, 'products': products}
return render(request, 'accounts/products.html', context)
hope you can direct me to the right place.
thank you!
if form.is_valid():
order = get_object_or_404(Order, id=id)
instance = form.save(commit=False)
instance.order=order
instance.save()
just need to do:
commit=False
and then link the order.