Django annotate with aggregated average value - python

In the following example from django documentation, how to get
Publisher.objects.all()
annotated with field average_rating computed using average of book ratings and max_rating computed using maximum rating of books?
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Publisher(models.Model):
name = models.CharField(max_length=300)
num_awards = models.IntegerField()
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
pubdate = models.DateField()
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
registered_users = models.PositiveIntegerField()
Precisely I should be able to print something like this after the queryset:
for p in Publisher.objects.all().annotate(...):
print p, p.average_rating, p.max_rating

You can access books of publisher using book__rating like this:
Publisher.objects.annotate(average_rating=Avg('book__rating'), max_rating=Max('book__rating'))

Related

Django Models to calculate discount

I am doing an ecommerce project as my first django project and I am having some trouble on how to calculate my actual price and my discount price if there is a discount price so what I want to do is that if the admin adds a discount to a product I want to add a value to a field inside a model called discount price and in that model I want to calculate how much discount percentage the admin has put in and what the discounted price would be after applying the discount percentage
ps: English is my second language and I'm sorry if you were not able to understand
tldr : I want to calculate the price and the discount percentage and make the value it to another field in the model called discount price
this is my models for the product and discounts(please point out how I should improve and any of my mistakes)
from django_extensions.db.fields import AutoSlugField
from django.core.validators import MinValueValidator, MaxValueValidator
# Create your models here.
class Products(models.Model):
product_name = models.CharField(max_length=200, unique=True)
slug = AutoSlugField(populate_from=['product_name'], unique=True)
description = models.TextField(max_length=500, blank=True)
price = models.IntegerField(validators = [MinValueValidator(0)])
discount_price = models.IntegerField(validators = [MinValueValidator(0)],null=True)
image1 = models.ImageField(upload_to='photos/Products')
image2 = models.ImageField(upload_to='photos/Products')
image3 = models.ImageField(upload_to= 'photos/Products')
image4 = models.ImageField(upload_to= 'photos/Products')
stock = models.IntegerField(validators=[MinValueValidator(0)])
Is_available = models.BooleanField(default=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = 'products'
verbose_name_plural = 'products'
def get_url(self):
return reverse('product_page',args=[self.category.slug, self.slug])
def __str__(self):
return self.product_name
class OfferProduct(models.Model):
product = models.OneToOneField(Products, related_name='category_offers', on_delete=models.CASCADE)
discount = models.IntegerField(validators=[MinValueValidator(0),MaxValueValidator(99)],null=True,default = 0)
is_active = models.BooleanField(default =True)
class Meta:
verbose_name = 'Offer Product'
verbose_name_plural = 'Offer Products'
def __str__(self):
return self.product.product_name
========= model.py =================
class ProductModel(models.Model):
name= models.CharField(max_length=300)
og_price = models.IntegerField()
discount = models.IntegerField()
discounted_price = models.IntegerField(null=True)
sell_price = models.IntegerField(null=True)
created_at = models.DateField(auto_now_add=True)
#property
def discounted_price(self):
return ((self.og_price)*(self.discount))/100
#property
def sell_price(self):
return (self.og_price)-(self.discounted_price)
=========== Output ============
example : price : 1000, discount: 100 so the percentage is 10%
you can add a property in the OfferProduct:
#property
def discount_percentage(self):
return (100 * discount)/product.price #add your logic

Get data from Inherit Model Django

Im working in my Python Django ecommerce project.Now i have 2 classes Item and BookItem :
class Item(models.Model):
item_name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200,unique=True)
description = models.TextField(max_length=500, blank=True)
price = models.IntegerField()
images = models.ImageField(upload_to='photos/products')
stock = models.IntegerField()
is_available = models.BooleanField(default = True)
category = models.ForeignKey(Category,on_delete = models.CASCADE)
created_date = models.DateTimeField(auto_now=True)
modified_date= models.DateTimeField(auto_now=True)
def __str__(self):
return self.item_name
def get_url(self):
return reverse('item_detail',args=[self.category.slug, self.slug])
class BookItem(Item):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
I want to get BookItem data from the class Item.Anyone knows how to do it ?
Get Book data for all Items
Item.objects.all().values(
"book__book_name",
"book__import_price",
# "class_name__field_name", structure of the query
)
To filter Item data using Book fields
[filter Items where book name is 'bookname']
Item.objects.filter(book__book_name="bookname")

Django - Join 3 tables to get records

Need to join these 3 tables , can someone give me the ORM queryset . need to show the records on one template based on these three tables.
Models.py
class Item_Table(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=127)
description = models.TextField(null=True,blank=True)
qty_in_ferma_warehouse = models.IntegerField(null=True,blank=True,default=0)
status = models.BooleanField()
ListID = models.CharField(max_length=80, null=True,blank=True)
class Order_Table(models.Model):
id = models.AutoField(primary_key=True)
order_number = models.CharField(max_length=63)
notes = models.TextField()
created_at = models.DateField()
status = EnumField(Choice,max_length=2, null=True,blank=True)
Total_Amount = models.DecimalField(max_digits=18,decimal_places=2)
must_fill_in_items = models.IntegerField()
total_replenish_small_order = models.IntegerField()
order_type = EnumField(Choice3,max_length=2, null=True,blank=True)
delivery_method = EnumField(Choice6, max_length=2, null=True, blank=True)
class Orderitems_Table(models.Model):
id = models.AutoField(primary_key=True)
order_id = models.ForeignKey(Order_Table,on_delete='')
item_id = models.ForeignKey(Item_Table,on_delete='')
qty = models.IntegerField()
next_order_qty = models.IntegerField(null=True,blank=True,default=0)
Rate = models.DecimalField(max_digits=18,decimal_places=2)
Amount = models.DecimalField(max_digits=18,decimal_places=2)
status = EnumField(Choice2,max_length=2,null=True,blank=True)
accumulated_residual_item = models.IntegerField()
accumulated_damaged_item = models.IntegerField()
You can have a many to many field in Order_Table.
items = models.ManyToManyField(Person, through='Orderitems_Table')
then you can query on Order_Table model and have a queryset
you can go through the documentation to have more insights about ManyToMany Field and how to play with this
For forms and view you can follow this link

Django 1.11 not recognising Foreign Key model assignments

I am having an issue with 2 Foreign Key assignments in my django model. See models.py below:
from django.db import models
from django.contrib.auth.models import User
class userData(models.Model):
user = models.ForeignKey(User)
house = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=True, null=True)
street = models.CharField(max_length=150)
state = models.CharField(max_length=100)
postcode = models.CharField(max_length=20)
country = models.CharField(max_length=100)
telephone = models.CharField(max_length=20)
subscription = models.IntegerField(default=0)
active = models.IntegerField(default=0)
class area(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class country(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class city(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class foodType(models.Model):
food_type_name = models.CharField(max_length=100)
class restaurant(models.Model):
restaurant_name = models.CharField(max_length=100)
food_type = models.ForeignKey(foodType)
area = models.ForeignKey(area)
country = models.ForeignKey(country)
city = models.ForeignKey(city)
date_added = models.DateField()
main_image = models.ImageField(blank=True, null=True)
website = models.URLField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
featured = models.IntegerField(default=0)
class restaurantFeature(models.Model):
feature_name = models.CharField(max_length=100)
restaurant_id = models.ForeignKey(restaurant)
Django Foreign Key not working correctly
The image shows the Country and City, not showing correctly, like the FoodType and Area does. Theses show with the + buttons for adding, the mysql database is showing the key next to the fields. I have also tried renaming country and City adding Location after, thinking it could be something with these names.
Appreciate any help with this one.
You're having this issue because you need to reference ALL the models inside the admin.py. Django admin doesn't know what you're referencing.

How django aggregation with foreign key work?

I have a model:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Publisher(models.Model):
name = models.CharField(max_length=300)
num_awards = models.IntegerField()
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
pubdate = models.DateField()
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
registered_users = models.PositiveIntegerField()
I could not understand how the following code work
This is from the django official Documentation, in the cheat sheet.
https://docs.djangoproject.com/en/1.10/topics/db/aggregation/
What I am trying to do is count the total votes for the following model
I use Question.objects.filter(owner_id=1).annotate(total_votes=Sum('votes')) as in the documentation. But this not work for me.
class Question(models.Model):
question_text = models.CharField('Question',max_length=200)
pub_date = models.DateTimeField('date published')
owner = models.ForeignKey(User,default=DEFAULT_USER_ID)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
Your Question model doesn't have votes your Choice model does
Question.objects.filter(owner_id=1).annotate(total_votes=Sum('choice__votes'))

Categories