AttributeError: 'Order' object has no attribute 'shipping' - python

Learning Django with Tutorial.
In the end of lesson I have error:
AttributeError: 'Order' object has no attribute 'shipping'.
I can't understand what's wrong.
Error in PyCharm Terminal
I understand that Order must have shipping attribute, but cant find where exactly looking that.
Sorry for bad english.
My project files:
checkout.html
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank=False)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=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)
#property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_addet = models.DateTimeField(auto_now_add=True)
#property
def get_total(self):
total = self.product.price * self.quantity
return total
class ShippingAddress(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
address = models.CharField(max_length=200, null=False)
city = models.CharField(max_length=200, null=False)
state = models.CharField(max_length=200, null=False)
zipcode = models.CharField(max_length=200, null=False)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.address
views.py
from django.shortcuts import render
from django.http import JsonResponse
import json
import datetime
from .models import *
def store(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']
products = Product.objects.all()
context = {'products':products, 'cartItems':cartItems}
return render(request, 'store/store.html', context)
def cart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']
context = {'items':items, 'order':order, 'cartItems':cartItems}
return render(request, 'store/cart.html', context)
def checkout(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
else:
items = []
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
cartItems = order['get_cart_items']
context = {'items':items, 'order':order, 'cartItems':cartItems}
return render(request, 'store/checkout.html', context)
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print('Action', action)
print('productId', productId)
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
if action == 'add':
orderItem.quantity = (orderItem.quantity + 1)
elif action == 'remove':
orderItem.quantity = (orderItem.quantity - 1)
orderItem.save()
if orderItem.quantity <=0:
orderItem.delete()
return JsonResponse('Item was added', safe=False)
def processOrder(request):
transaction_id = datetime.datetime.now().timestamp()
data = json.loads(request.body)
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
total = float(data['form']['total'])
order.transaction_id = transaction_id
if total == float(order.get_cart_total):
order.complete = True
order.save()
if order.shipping == True:
ShippingAddress.objects.create(
customer=customer,
order=order,
address=data['shipping']['address'], #порядок как в models
city=data['shipping']['city'],
state=data['shipping']['state'],
zipcode=data['shipping']['zipcode'],
)
else:
print('User is not logged in...')
return JsonResponse('Payment complete!', safe=False)
models.py
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank=False)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=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)
#property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_addet = models.DateTimeField(auto_now_add=True)
#property
def get_total(self):
total = self.product.price * self.quantity
return total
class ShippingAddress(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
address = models.CharField(max_length=200, null=False)
city = models.CharField(max_length=200, null=False)
state = models.CharField(max_length=200, null=False)
zipcode = models.CharField(max_length=200, null=False)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.address
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.store, name="store"),
path('cart/', views.cart, name="cart"),
path('checkout/', views.checkout, name="checkout"),
path('update_item/', views.updateItem, name="update_item"),
path('process_order/', views.processOrder, name="process_order"),
]
I reviewed the lesson several times, code seems to be without mistakes.

Server side error
The error is because you didn't declared shipping variable in your Orders model.
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
shipping = models.CharField(max_length=200, null=True)
def __str__(self):
return str(self.id)
#property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
Go to models file and update the Order class with above code.
client side
While making API request set the header Content-Type to text/html.
Because the API is responding HTML file not json.
That's why you have an error in browser.

in Order model there should be a field named shipping which is require in the processorder view.
just add below field in Order model
shipping = models.BooleanField(default=False)
since you want ot hide it , then a property need to be added not the db field
so your model should look like this
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
#property
def shipping(self):
shipping = False
# add shipping logic here
return shipping
def __str__(self):
return str(self.id)
#property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
follow the tutorial a little more, you will be able to grasp the solution.

Related

Cannot assign "OrderItem.product" must be a "Product" instance

I am trying to create a "create order" endpoint, i keep getting
Cannot assign "<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7f50dad00f70>": "OrderItem.product" must be a "Product" instance.
heres my models
def product_images(instance, filename):
return f"product/{instance.product_name}/{filename}"
class Product(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=200, null=True, blank=True)
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
image = models.ImageField(
storage=MediaRootS3BotoStorage(),
upload_to="product_images",
null=True,
blank=True,
)
price = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return self.name
def save(self, *args, **kw):
self.slug = slugify(f"{self.name}")
super(Product, self).save(*args, **kw)
# Ecommerce Models Store and Product
def store_images(instance, filename):
return f"{instance.store_name}/{filename}"
class Store(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=200, null=True, blank=True)
description = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
image = models.ImageField(upload_to="store_images", null=True, blank=True)
delivery_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
address = models.CharField(max_length=100, null=True, blank=True)
phone_number = models.CharField(max_length=100, null=True, blank=True)
products = models.ManyToManyField("Product", through="StoresProduct")
def __str__(self):
return self.name
def save(self, *args, **kw):
self.slug = slugify(f"{self.name}")
super(Store, self).save(*args, **kw)
class Cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ManyToManyField("Product", through="StoresProduct")
quantity = models.IntegerField(default=1)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.email
def get_total(self):
return self.product.price * self.quantity
class StoresProduct(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
seller = models.ForeignKey(Store, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
quantity = models.IntegerField(blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
cart = models.ForeignKey(
Cart,
on_delete=models.CASCADE,
related_name="products",
default=None,
null=True,
blank=True,
)
product = models.ForeignKey(
Product,
on_delete=models.CASCADE,
related_name="+",
default=None,
null=True,
blank=True,
)
def __str__(self):
return f"{self.product.name} - {self.seller.name}"
class Meta:
unique_together = ["product", "seller"]
OrderStatus = (
("Pending", "Pending"),
("Delivered", "Delivered"),
("Cancelled", "Cancelled"),
("Processing", "Processing"),
)
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=100, choices=OrderStatus, default="Pending")
delivery_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
order_id = models.CharField(max_length=100, null=True, blank=True)
order_items = models.ManyToManyField("Product", through="OrderItem")
store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return self.user.email + " - " + self.order_id
def get_random_order_id(self):
order_id = str(uuid.uuid4()).replace("-", "").upper()[:10]
return order_id
# create order id with random string
def save(self, *args, **kwargs):
if not self.order_id:
self.order_id = self.get_random_order_id()
super(Order, self).save(*args, **kwargs)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
order = models.ForeignKey(Order, on_delete=models.CASCADE)
store = models.ForeignKey(Store, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.product.name
and my views.py
#create order with orderitems
#swagger_auto_schema(method="post", request_body=OrderSerializer)
#api_view(["POST"])
#permission_classes((permissions.AllowAny,))
#authentication_classes([TokenAuthentication])
def create_order(request):
"""
Creates an order then creates an orderitem
"""
user = request.user
serializer = OrderSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=user)
order_id = serializer.data["id"]
order = Order.objects.get(pk=order_id)
cart = user.cart_set.all()
for item in cart:
OrderItem.objects.create(
order=order,
product=item.product,
quantity=item.quantity,
)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#swagger_auto_schema(method="post", request_body=AddToCartSerializer)
#api_view(["POST"])
#permission_classes((permissions.AllowAny,))
#authentication_classes([TokenAuthentication])
def add_to_cart(request):
"""
Adds a product to cart
"""
user = request.user
serializer = AddToCartSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Basically, users should be able to add products from various stores to their cart and when they are done they should be able to order.
I can't seem to figure out what i am doing wrongly, if there's a better way to do this do tell.I'm guessing my approach is problematic

I am getting ERROR: AttributeError at /customer/5/ type object 'Customer' has no attribute 'orderitem_set'

Please help me I stuck at this problem. When Click on the view button I want to show all the orders from that user as shown in the image below, but when i click on it I am getting this error instead of order details for that customer.
The models file contains
models.py
class Customer(models.Model):
user = models.OneToOneField(
User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=50, null=True)
phone = models.CharField(max_length= 200, null = True)
email = models.CharField(max_length=100)
def __str__(self):
return self.name
class Order(models.Model):
customer = models.ForeignKey(
Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False, null=True, blank=True)
transaction_id = models.CharField(max_length=200, null=True)
def __str__(self):
return str(self.customer)
#property
def shipping(self):
shipping = False
orderitems = self.orderitem_set.all()
for i in orderitems:
if i.product.digital == False:
shipping = True
return shipping
#property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
class OrderItem(models.Model):
customer = models.ForeignKey(
Customer, on_delete=models.SET_NULL, null=True, blank=True)
product = models.ForeignKey(
Product, on_delete=models.SET_NULL, null=True, blank=True)
order = models.ForeignKey(
Order, on_delete=models.SET_NULL, null=True, blank=True)
quantity = models.IntegerField(default=0, null=True, blank=False)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.product.name
#property
def get_total(self):
total = self.product.price * self.quantity
return total
The views.py file contains
Views.py
#login_required(login_url='login')
#admin_only
def customer(request, pk):
customer = Customer.objects.get(id=pk)
orders = Customer.orderitem_set.all()
shippinginfo = customer.shippingaddress_set.all()
total_order = orders.count()
context = {'customer': customer, 'orders': orders, 'total_order':total_order, 'shippinginfo': shippinginfo}
return render(request, 'store/customer.html', context)
Do it like :-
def customer(request, pk):
customer = Customer.objects.get(id=pk)
orders = customer.orderitem_set.all()
shippinginfo = customer.shippingaddress_set.all()
total_order = orders.count()
What i have changed ?
I have related (connected) orderitem_set with the existing id with existing query.
EDIT :-
I have found the problem in your GitHub Repo.
The Problem is in the updateItem view.
You're saving the order but you're not relating the request.user as a customer with the order.
So do it like :-
def updateItem(request):
data = json.loads(request.body)
productID = data['productID']
action = data['action']
print('Action:', action)
print('productID:', productID)
customer = request.user.customer
product = Product.objects.get(id=productID)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
if action == 'add':
orderItem.quantity = (orderItem.quantity + 1)
elif action == 'remove':
orderItem.quantity = (orderItem.quantity - 1)
# Add this line
orderItem.customer = request.user.customer
orderItem.save()
if orderItem.quantity <= 0:
orderItem.delete()
return JsonResponse('Item was added', safe=False)
Add a related_name field in your models.py on Order model like
class Order(models.Model):
customer = models.ForeignKey(
Customer, on_delete=models.SET_NULL, null=True, blank=True, related_name="orders")
And then in views.py
def customer(request, pk):
customer = Customer.objects.get(id=pk)
orders = customer.orders.all()

Django _set.all() filter in QuerySet

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

AttributeError: 'QuerySet' object has no attribute 'product' ERROR

Hi I'm building a Webshop with a cart and checkout function. Now I'm trying to add the products and their quantity to an Email form which I want to send to an email obviously but I don't know how I could get the item.name or the item.quantity without getting an error as shown below.
I have the following 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)
email = models.CharField(max_length=200)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank=False) # Nicht nötig
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False, null=True, blank=False)
transaction_id = models.CharField(max_length=200, null=True)
def __str__(self):
return str(self.id)
#property
def get_cart_total(self):
orderitems = self.orderitem_set.all()
total = sum([item.get_total for item in orderitems])
return total
#property
def get_cart_items(self):
orderitems = self.orderitem_set.all()
total = sum([item.quantity for item in orderitems])
return total
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
#property
def get_total(self):
total = self.product.price * self.quantity
return total
So I'm trying to get the product name and quantity from an Query set. But I get an error as described in the title
AttributeError: 'QuerySet' object has no attribute 'product'.
I'm trying to append the product name and quantity a customer has selected to a message variable which will be send to an email with sendmail().
This is my view:
#login_required(login_url='login')
def checkout(request):
if request.method == "POST":
message_name = request.POST['message-name']
message_email = request.POST['message-email']
message = request.POST['message']
message_to_send = str(message)
# send an email
send_mail(
'message from ' + message_name, # subject
message_to_send, # message
message_email, # from email
['jeampo#outlook.de'], # To Email
)
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
cartItems = order.get_cart_items
print(items.product.name)
print(items.quantity)
context = {'items': items, 'order': order, 'cartItems': cartItems}
return render(request, 'store/checkout.html', context)
Thank you for any help.
You are calling items.product.name in your print statement, but items is a set of objects not just a single object.
You can fix this by using the following code in your views.py in place of print(items.product.name)
for item in items:
print(item.product.name)
You can also reference this directly in your template, by using the {% for %} code.
Example:
Inside your template.html
{% for item in items %}
<h1>{{item.product.name}}</h1>
{% endfor %}

how to fetch table field in other field

I have a cart and subcategory model. I want to fetch the price of the service. How I fetch the price of service in the price field.
I want to fetch price of service in the price field.
Here is my models.py
class SubCategory(models.Model):
name = models.CharField(max_length=254, unique=True)
id_parent = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
price = models.IntegerField()
status = models.BooleanField(default=True)
def __str__(self):
return self.name
class Cart(models.Model):
user = models.ForeignKey('accounts.User', related_name="carts", null=True, on_delete=models.SET_NULL)
quantity = models.IntegerField(default=1)
service = models.ForeignKey('accounts.SubCategory',null=True, on_delete=models.SET_NULL)
price = models.ForeignKey('accounts.SubCategory', on_delete=models.CASCADE, default=None, blank=True, related_name='subprice')
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.price.price)
You would not need to select a value for price since it's derived from the service you selected.
class SubCategory(models.Model):
name = models.CharField(max_length=254, unique=True)
id_parent = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
price = models.IntegerField()
status = models.BooleanField(default=True)
def __str__(self):
return self.name
class Cart(models.Model):
user = models.ForeignKey('accounts.User', related_name="carts", null=True, on_delete=models.SET_NULL)
quantity = models.IntegerField(default=1)
service = models.ForeignKey('accounts.SubCategory',null=True, on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.service.price) # if you want just the price of the single service
#property
def total_price(self):
if self.service is not None:
return self.service.price * self.quantity
return 0
service = SubCategory(name="Help with Django", price=5)
aCart = Cart(user=1, quantity=2, service=service)
print(aCart.total_price) # 10
If I understand you clear, you just want to get price of SubCategory attached to Cart. If so, you don't need to add price field to Cart model to get SubCategory price.
You can just define price property on Cart model like this and use it in admin like a regular field:
class Cart(models.Model):
user = models.ForeignKey('accounts.User', related_name="carts", null=True, on_delete=models.SET_NULL)
quantity = models.IntegerField(default=1)
service = models.ForeignKey('accounts.SubCategory',null=True, on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True)
#property
def price(self):
if self.service:
return self.service.price
return None
#property
def total(self):
if self.service:
return self.service.price * self.quantity
return None
def __str__(self):
if self.price:
return str(self.price)
return "Can't show price with no service selected"

Categories