How to show child table in Django REST Framework API view - python

I'm using Django as Backend, PostgresSQl as DB and HTML, CSS and Javascript as Frontend. I want to show Children Table in DJANGO REST FRAMEWORK, as I'm using Multi Table Inheritance.
As we can see in above image, that only Product list is been displayed but not the children table. I want to show all the data which is selected by customer. I'm showing Cart Product in DRF
views.py
class AddToCartView(TemplateView):
template_name = "status.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
product_id = self.kwargs['pk']
product_obj = Product.objects.get(id = product_id)
cart_id = self.request.session.get("cart_id", None)
if cart_id:
cart_obj = Cart.objects.get(id = cart_id)
this_product_in_cart = cart_obj.cartproduct_set.filter(product = product_obj)
if this_product_in_cart.exists():
cartproduct = this_product_in_cart.last()
cartproduct.quantity += 1
cartproduct.subtotal += product_obj.price
cartproduct.save()
cart_obj.total += product_obj.price
cart_obj.save()
else:
cartproduct = CartProduct.objects.create(
cart = cart_obj, product = product_obj, rate = product_obj.price, quantity = 1, subtotal = product_obj.price)
cart_obj.total += product_obj.price
cart_obj.save()
else:
cart_obj = Cart.objects.create(total=0)
self.request.session['cart_id'] = cart_obj.id
cartproduct = CartProduct.objects.create(
cart = cart_obj, product = product_obj, rate = product_obj.price, quantity = 1, subtotal = product_obj.price)
cart_obj.total += product_obj.price
cart_obj.save()
return context
API View (views.py)
#api_view(['GET'])
def showproduct(request):
result = CartProduct.objects.all()
serialize = productserializers(result, many = True)
return Response(serialize.data)
models.py
class Product(models.Model):
name = models.CharField(max_length=1330)
image_src = models.URLField(max_length=1330,null=True, blank=True)
link_href = models.URLField(max_length=1330,null=True, blank=True)
brand = models.CharField(max_length = 1330, null=True, blank=True)
price = models.DecimalField(max_digits=15, decimal_places=2)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created',)
class Refrigerator(Product):
series = models.CharField(max_length = 300, null=True, blank=True)
model = models.CharField(max_length = 300, null=True, blank=True)
...
class Cart(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
total = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "Cart: " + str(self.id)
class CartProduct(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
rate = models.PositiveIntegerField()
quantity = models.PositiveIntegerField()
subtotal = models.PositiveIntegerField()
def __str__(self):
return "Cart: " + str(self.cart.id) + " CartProduct: " + str(self.id)
I want to show refrigerator details aslo in DRF which is been selected by customer.
serializer.py
class productserializers(serializers.ModelSerializer):
class Meta:
model = CartProduct
fields = "__all__"
depth = 2

You can try this, in your Product(models.Model)
class Meta:
abstract = True
you can refer here for explanation : here
(I should have comment this but don't have enough reputations for that :/)

Related

How To Automatically Create Objects Of Django Model While Creation Another Model Objects

I Want To Create Object For "ProductOut" Model When "CusOrder" Model Is Being Created
Here Is My Code
class CusOrder(models.Model):
cus_name = models.CharField(max_length=100)
cus_number = models.CharField(max_length=11)
product = models.ManyToManyField(Product)
qty = models.IntegerField(default=0)
sell_price = models.IntegerField(default=0)
def __str__(self):
return self.cus_name
def save(self,*args,**kwrgs):
ProductOut.objects.create(
refrence=self.cus_number,
stock_out = self.qty,
sell_price = self.sell_price,
product = self.product.P_name
)
super(CusOrder,self).save(*args,**kwrgs)
class ProductOut(models.Model):
refrence = models.ManyToManyField(CusOrder)
stock_out = models.IntegerField(default=0)
sell_price = models.IntegerField(default=0)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
def __str__(self):
return self.refrence.cus_number
But I am Getting a ValueError which Is '"<CusOrder: Asif>" needs to have a value for field "id" before this many-to-many relationship can be used.' When I want to save a CusOrder Object
here Is My Whole
class Catagory(models.Model):
name = models.CharField(max_length=60)
def __str__(self):
return self.name
class Product(models.Model):
P_name = models.CharField(max_length=30)
stock_in = models.IntegerField(default=0)
unit_price = models.IntegerField(default=0)
cata = models.ForeignKey(Catagory, on_delete=models.CASCADE)
def __str__(self):
return self.P_name
class CusOrder(models.Model):
cus_name = models.CharField(max_length=100)
cus_number = models.CharField(max_length=11)
product = models.ManyToManyField(Product)
qty = models.IntegerField(default=0)
sell_price = models.IntegerField(default=0)
def __str__(self):
return self.cus_name
def save(self,*args,**kwrgs):
ProductOut.objects.create(
refrence=self.cus_number,
stock_out = self.qty,
sell_price = self.sell_price,
product = self.product.P_name
)
super(CusOrder,self).save(*args,**kwrgs)
class ProductOut(models.Model):
refrence = models.ManyToManyField(CusOrder)
stock_out = models.IntegerField(default=0)
sell_price = models.IntegerField(default=0)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
def __str__(self):
return self.refrence.cus_number
class ReturnedProduct(models.Model):
cus_number = models.ForeignKey(CusOrder,on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
qty = models.IntegerField(default=0)
def __str__(self):
return self.cus_number.cus_number
What Will Be The Right Proccess To Do That.
refrence should have CusOrder instance and super should call before the creation as CusOrder object should be created first.
def save(self,*args,**kwrgs):
instance = super(CusOrder,self).save(*args,**kwrgs)
p_instance = ProductOut.objects.create(
stock_out = self.qty,
sell_price = self.sell_price,
product = self.product.first()
)
p_instance.refrence.add(instance)
p_instance.save()
Best way is to use Django Signals, In above case specifically use post_save. Django Signals- master pre_save and post_save

Error 'Product' object has no attribute '_combinator_query'

I am creating an e-commerce website in django where the homepage can be changed dynamically by changing the instances of FeaturedProduct objects. These objects have two ForeignKeys. First is to the Product class and the other is to FeaturedCategory class(this is for the type of deal, eg: daily deals, new arrivals, etc). So, I'm trying to get the Product instances in a queryset instead of the FeaturedProduct queryset. When I union two querysets, I get an error that 'Product' object has no attribute '_combinator_query'. The codes have been shown below.
My models.py
class Product(models.Model):
product_id = models.AutoField
product_name = models.CharField(max_length=50, unique=True)
category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default='1')
sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_DEFAULT, default='2')
price = models.IntegerField(default=0)
stock = models.IntegerField(default=0)
desc = models.TextField()
pub_date = models.DateField()
avg_rating = models.IntegerField(default=0)
avg_rating_float = models.FloatField(default=0.0)
number_of_ratings = models.IntegerField(default=0)
image1 = models.ImageField(upload_to="images", default="")
image2 = models.ImageField(upload_to="images", default="")
image3 = models.ImageField(upload_to="images", default="")
slug = models.SlugField(blank=True, help_text=('Leave this parameter empty, it will get generated automatically.'))
def save(self, *args, **kwargs):
self.slug = slugify(self.product_name)
super(Product, self).save(*args, **kwargs)
def __str__(self):
return self.product_name
class FeaturedCategory(models.Model):
category = models.CharField(max_length=100)
def __str__(self):
return self.category
class Meta:
verbose_name_plural = "Featured Categories"
class FeaturedProduct(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
featured_category = models.ForeignKey(FeaturedCategory, on_delete=models.CASCADE)
def __str__(self):
return self.product.product_name
My views.py
def index(request):
prod = Product.objects.none()
feat = FeaturedProduct.objects.all()
for pro in feat:
ob = Product.objects.get(product_name=pro.product)
print(ob.product_name)
print(ob.category)
print(ob.sub_category)
print(ob.price)
prod.union(ob) # Error found here
# Working part
products = Product.objects.all()
context = {'products': products}
return render(request, 'index.html', context)
The last three lines are working fine, but not the other part of the index function.
Please help. Thank You.

Shopping cart DB not showing number of Individual Items Ordered

I'm trying to create a shopping cart model, I've created the Order Model, OrderItem model and Also the Item model. Although I find it difficult to link the order it model to the order in the API view.
here's the Model
class Pizza(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
desc = models.CharField(max_length=150)
price = models.IntegerField()
url = models.CharField(max_length=250)
def __str__(self):
return self.name
class OrderItem(models.Model):
id = models.AutoField(primary_key=True)
product = models.ForeignKey("Pizza", on_delete=models.CASCADE, null=True)
date_added = models.DateTimeField(auto_now=True)
date_ordered = models.DateTimeField(null=True)
amount = models.IntegerField(null=True)
def __str__(self):
return self.product.name
class Order(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
email = models.CharField(max_length=150)
address = models.CharField(max_length=150)
total = models.IntegerField()
created_at = models.DateTimeField(default=timezone.now)
items = models.ManyToManyField(OrderItem)
def __str__(self):
return self.name
//The viewset
class OrderViewSet(viewsets.HyperlinkedModelSerializer):
# permission_classes = [IsPostOrIsAuthenticated,]
serializer_class = OrderSerializer
queryset = Order.objects.all().order_by('-created_at')
Currently, I cant display the amount attribute of the order item in my API, It just shows the id and Also the link to the individual orderitem in an order
I think for cart you can use external fields on relations between Order and Pizza. Documentation about this here
Your models looks like:
class Pizza(models.Model):
name = models.CharField(max_length=60)
desc = models.CharField(max_length=150)
price = models.IntegerField()
url = models.CharField(max_length=250)
def __str__(self):
return self.name
class Order(models.Model):
name = models.CharField(max_length=60)
email = models.CharField(max_length=150)
address = models.CharField(max_length=150)
total = models.IntegerField()
created_at = models.DateTimeField(auto_now=True)
items = models.ManyToManyField(Pizza, through='OrderItem')
def __str__(self):
return self.name
class OrderItem(models.Model):
product = models.ForeignKey('Pizza', on_delete=models.CASCADE, null=True)
order = models.ForeignKey('Order', on_delete=models.CASCADE, null=True)
date_added = models.DateTimeField(auto_now=True)
date_ordered = models.DateTimeField(null=True)
amount = models.IntegerField(null=True)
def __str__(self):
return self.product.name
Example, how you can get dict of items amount in order:
order = Order.objects.filter('-created_at').first() // get last order
cart = {item.pk: item.amount for item in order.items}

Getting the entries of a ManyToManyField

I'm working with a ManyToManyField and using a ModelMultipleChoice on form, I want to get the entries, but all I get is appname.Extra.none
models.py
class Extra(models.Model):
extra_n = models.CharField(max_length=200)
extra_price = models.IntegerField(default=0)
def __str__(self):
return self.extra_n
class Meal(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.PROTECT)
category = models.ForeignKey(MealCategory, on_delete=models.PROTECT)
name = models.CharField(max_length=500)
short_description = models.CharField(max_length=500)
image = models.ImageField(upload_to='meal_images/', blank=False)
price = models.IntegerField(default=0)
extras = models.ManyToManyField(Extra, related_name='extras')
def __str__(self):
return self.name
forms.py
class MealForm(forms.ModelForm):
extras = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Meal.extras)
class Meta:
model = Meal
exclude = ("restaurant",)
views.py
def restaurant_meal(request):
meals = Meal.objects.filter(restaurant = request.user.restaurant).order_by("-id")
return render(request, 'restaurant/meal.html', {"meals": meals})
The output desired is getting the extras added displayed on restaurant_meal view.
you can try change
meals = Meal.objects.filter(restaurant = request.user.restaurant).order_by("-id")
to
meals = Meal.objects.filter(restaurant = request.user.restaurant).prefetch_related('extras').order_by("-id")
and try again.
Doc of this in prefetch_related

How to use two model forms on one view

I'm still new to django, I'm working on a project where I'll need users to enter some information about houses they want to rent out. I want the users to upload a minimum of 6 pictures and from what I've gathered, the best way to do this on django is to use two models, one collects basic information about the houses and the second stores images of the houses. How am I supposed to code the views.py. I've tried all to no avail.
forms.py
class MyHouseEditForm(forms.ModelForm):
class Meta:
model = Myhouses
fields = ('name_of_accomodation',
'type_of_apartment','Number_of_rooms', 'house_rent',
'availability', 'location', 'nearest_institution',
'description',)
class ImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ('__all__' )
models.py
class Myhouses(models.Model):
Available = 'A'
Not_Available = 'NA'
Availability = (
(Available, 'Available'),
(Not_Available, 'Not_Available'),
)
Flat = 'F'
Self_contained = 's'
Bungalow = 'b'
Mini_flat = 's'
Duplex = 'D'
Room = (
(Flat, 'Flat'),
(Self_contained, 'Self_contained'),
(Bungalow, 'Bungalow'),
(Mini_flat, 'Mini_flat'),
(Duplex, 'Duplex'),
)
time = models.DateTimeField(default = datetime.now, blank = True)
name_of_accomodation = models.CharField(max_length=20)
type_of_apartment = models.CharField(max_length=2, choices=Room, )
Number_of_rooms = house_rent = models.IntegerField()
house_rent = models.IntegerField()
availability = models.CharField(max_length=2, choices=Availability, default=Available,)
location = models.CharField(max_length=200)
nearest_institution = models.CharField(max_length=200)
description = models.TextField(blank=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='author')
def __str__(self):
return self.name_of_accomodation
def get_absolute_url(self):
return reverse('search-detail', args=[str(self.id)])
class Meta:
ordering = ["-time"]
class Image(models.Model):
myhouses = models.ForeignKey(Myhouses, related_name='images', on_delete=models.PROTECT)
image = models.ImageField(upload_to='documents/')
views.py
def addlisting(request):
if request.method == 'POST':
Hform = MyHouseEditForm(request.POST, files=request.FILES, )
Iform = ImageForm(request.POST, request.FILES, )
if Hform.is_valid() and Iform.is_valid():
Houses = Hform.save(commit=False)
Houses.author=request.user
Houses.save()
image = iform.save(commit=False)
Houses.image.myhouses = myhouses
Houses.save()
messages.success(request, 'Listing Created Succesfully successfully')
return redirect('addlisting')
else:
Hform = MyHouseEditForm()
Iform = ImageForm()
return render(request, 'houses/addlisting.html', {'Hform':Hform, 'Iform': Iform}, )

Categories