I need to do a software for a "restaurant" and it needs to be able to calculate prices for the dishes that need to be cooked taking the prices from a list of ingredients. I imagine that the Dishes model would need a field called ingredients or one field for each ingredient (?), but i dont know how it would fetch the Ingredients model for the prices for each ingredient and calculate the total based on the quantity that needs to be cooked. What would be the best method? Like to have a template that shows the price of each ingredient with its quantity and the total of all the ingredients.
Every Dish is composed of many Ingredient s and each Ingredient will be used in many Dishes so the following suggestion will be proper for your problem
class Dish(models.Model):
price = models.DecimalField(max_digits=5, decimal_places=2)
class Ingredient(models.Model):
price = models.DecimalField(max_digits=5, decimal_places=2)
class DishIngredient(models.Model):
dish = models.ForeignKey(Dish)
ingredient = models.ForeignKey(Ingredient)
quantity = models.IntegerField()
Related
I have such models structure and I need to get information about how many pizzas was ordered.
I did something like this PizzaOrder.objects.all().values('pizza').annotate(total=Count('pizza')). It works fine for orders where count in PizzaOrder equals to 1, but if count more than 1, it displays wrong count number. So I want somehow to connect Django Count with my field count in order to know how many pizzas was ordered.
models.py
class Pizza(models.Model):
name = models.CharField(max_length=256)
class Order(models.Model):
order_number = models.IntegerField(primary_key=True)
pizzas = models.ManyToManyField(to='Pizza', through='PizzaOrder')
class PizzaOrder(models.Model):
pizza = models.ForeignKey(
to=Pizza,
on_delete=models.PROTECT,
)
order = models.ForeignKey(
to=Order,
on_delete=models.PROTECT,
)
count = models.SmallIntegerField()
Instead of Count you need to use the Sum function:
# annotating on the orders:
orders = Order.objects.annotate(total=Sum('pizzaorder__count'))
for order in orders:
print(order.order_number, order.total)
# annotating on the pizzas:
pizzas = Pizza.objects.annotate(total=Sum('pizzaorder__count'))
for pizza in pizzas:
print(pizza.name, pizza.total)
# aggregating irrespective of order / pizza:
pizza_count = PizzaOrder.objects.aggregate(total=Sum('count'))['total']
print(pizza_count)
I have a django web project. There are products for sales points. The points can have similar and different products to sale. So, i have created many to many relationship between them.
class SalesPoint(models.Model):
pointID = models.IntegerField()
def __str__(self):
myStr = str(self.pointID) + "ID'li nokta"
return myStr
class Product(models.Model):
productID = models.IntegerField(verbose_name="Kaydedilecek ürünün ID'si", default=0)
productName = models.TextField(verbose_name="Kaydedilecek ürünün adı")
salesPoint = models.ManyToManyField(SalesPoint, verbose_name="Nokta ID", blank=False)
def __str__(self):
return self.productName
Then I have a web page asking the user what product wants to be predicted. In this page, i want to create choice fields, and first i want to ask user which point he/she wants, then according to this point, i want to show available products(products that only belong to that sales point) to user. How can i make it? Here is my querying page module.
class SalesPrediction(models.Model):
whichPoint = models.ForeignKey(SalesPoint, on_delete=models.CASCADE, default=0)
whichProduct = models.ForeignKey(Product, on_delete=models.CASCADE, default=0)
However, this show all the products and points, i want to show only related points and products.
I want to fetch name of movie with maximum rated movie with minimum 5 people rated in django.
My code :
model.py
class Movie(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
vote_count = models.IntegerField()
class Watchlist(models.Model):
userid = models.IntegerField()
movie_id = models.ForeignKey(Movie, on_delete=models.CASCADE)
rating = models.IntegerField()
what will be query to get movie with highest rating with minimum 5 people ?
I propose that you make some changes to your model. Normally ForeignKeys do not end with an id suffix, since Django will add a "twin field" with an _id suffix that stores the value of the target field. Furthermore you probably better make a ForeignKey to the user model. If you do not specify a primary key yourself, Django will automatically add an field named id that is an AutoField, hendce there is no need to add that manually. Finally you do not need to store the vote_count in a field of the Movie, you can retrieve that by counting the number of related Rating objects:
from django.conf import settings
class Movie(models.Model):
title = models.CharField(max_length=100)
class Rating(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete.models.CASCADE)
movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
rating = models.IntegerField()
Then we can retrieve the highest rated movie with:
from django.db.models import Avg, Count
higest_rated = Movie.objects.annotate(
rating=Avg('rating__rating'),
votes=Count('rating')
).filter(votes__gte=5).order_by('-rating').first()
Here the votes__gte=5 will filter such that it will only obtain Movies with five or more votes, and we order by rating in descending order.
I'd modify the model, moving out Rating entity related fields from Watchlist and Movie.
Add the "Rate" class, and then filter by two conditions:
Count(Rate for the exact Movie) > minimum threshold(e.g. 5)
AVG(rating score for the exact Movie) > minimum threshold(e.g. 5)
or, if you need top-rated movies, use Order by as it described in that answer
In your case, you could use Count and Average with Watchlist.Rating field
I'm trying to build an Inventory Model for a Django App that handles the sale of seeds. Seeds are stored and sold in packs of 3, 5, or 10 seeds of a single variety (for example: 3 pack of mustard seeds).
I want to add x amount of products to inventory with a price for each entry, and sell that product at that price for as long as that entry has items left(quantity field > 0) even if later entries have been made for the same product and presentation but at a different price, so i have the following model:
class Product(models.Model):
name = models.CharField(max_length=100)
class Presentation(models.Model):
seed_qty = models.IntegerField()
class Stock(models.Model):
date = models.DateField(auto_now=True)
quantity = models.IntegerField()
product = models.ForeignKey(Product, on_delete=models.CASCADE)
presentation = models.ForeignKey(Presentation, on_delete=models.CASCADE)
cost = models.FloatField(null=True, blank=True)
sell_price = models.FloatField(null=True, blank=True)
I'm wondering if I should actually relate Product and Stock with a ManyToMany field through a GeneralEntry intermediate model in which I'd store date_added, presentation and cost/price.
My issue is that when I add multiple Stock entries for the same product and presentation, I can't seem to query the earliest prices for each available (quantity>0) stock entry for each product.
What I've tried so far has been:
stock = Stock.objects.filter(quantity__gt=0).order_by('-date')
stock = stock.annotate(min_date=Min('date')).filter(date=min_date)
But that returns that max_date isn't defined.
Any ideas on how to query or rearrange this model ?
Thanks!
*** UPDATE : I wasn't using F() function from django.db.models.
Doing it like this works:
stock = Stock.objects.filter(quantity__gt=0).order_by('-date')
stock = stock.annotate(min_date=Min('date')).filter(date=F('min_date'))
Turns out I wasn't using F() function from django.db.models.
Doing it like this works:
stock = Stock.objects.filter(quantity__gt=0).order_by('-date')
stock = stock.annotate(min_date=Min('date')).filter(date=F('min_date'))
im doing some models and have a thought while designing them, here is an example: a bank buys stock shares, so one bank can have many stock shares and many stock shares can be bought from many banks, its a many to many relationship but when a bank buys a stock shares it has to keep a record of the price and the date/period/round of the purchase, works the same for a sale, o in order to keep record of all of that im doing a class something like this:
class Bank(models.Model):
name = models.Charfield()
money = models.IntegerField()
class StockShares(models.Model):
name = models.Charfield()
price = models.Charfield()
now to make a relationship i know i have to add
stock = models.ManyToManyField(StockShares)
but then how do i add the relationship attributes that only exist when a purchase or sale happens?
i was thinking maybe i can do something like this:
class Bank(models.Model):
name = models.Charfield()
money = models.IntegerField()
class StockShares(models.Model):
name = models.Charfield()
price = models.Charfield()
class Sale(models.Model):
bank = models.ForeignKey(Bank)
stockshares = models.ForeignKey(StockShares)
date = models.DateField()
quantity = models.ForeignKey()##this should be the quantity of stockshares sold in $ im just lazy to write it down
this is what i would to normaly without using django and inside a database manager
is there a way to aproach to this in django without doing an intermediate class to deal with the relationship? or im doing my thougth good and this is how things have to be done in django
pd: english is not my first language im doing my best here
thanks in advance for answering!
You are looking for an Extra fields on many-to-many relationships
Your code should look like this:
class Bank(models.Model):
name = models.Charfield()
money = models.IntegerField()
members = models.ManyToManyField(StockShares, through='Sale')
class StockShares(models.Model):
name = models.Charfield()
price = models.Charfield()
class Sale(models.Model):
bank = models.ForeignKey(Bank)
stockshares = models.ForeignKey(StockShares)
date = models.DateField()
Maybe quantity should be calculated field