Django: many to many relationship model definition - python

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

Related

SQLite Django Model for Inventory of Seeds

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'))

Linking one models with a set of another in Django

I am currently working on developing a database and API system where users can create a portfolio which contains a list of coins. I am using Django and I searched everywhere but I kept seeing foreign keys but I'm not sure that's what I need in this situation.
I want two models, one for portfolios which a user will be able to query on, and another coin model which the user will be able to also query on. However in the portfolio there should be a list of coins. I know how to do this in Java using objects but not sure the method in Django.
Here is my model class:
from django.db import models
class Portfolio(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return self.name
class Coin(models.Model):
name = models.CharField(max_length=100)
symbol = models.CharField(max_length=5)
price = models.DecimalField(max_digits=20, decimal_places=9)
info = models.TextField()
website = models.TextField()
rank = models.IntegerField()
def __str__(self):
return self.name + " - " + self.symbol
Now I would ideally have something like coins = list of Coins model if I was using java to make the objects, but since this is for a database and in Django I'm not sure how I should link the two.
I've seen related objects but did not understand the explanations for my issue. How should I go about setting up these models? Thanks.
It sounds like you want to have a number of Portfolio objects each of which can have varying investments in Coin objects. In this case, you'd want to use a ManyToManyField:
class Portfolio(models.Model):
name = models.CharField(max_length=250)
coins = models.ManyToManyField(Coin)
The database would then store the two dimensional table of which Portfolio holds which coin.
However an alternate approach you could try is to create an object that separately represents the investment:
class Investment(models.Model):
portfolio = models.ForeignKey(Portfolio)
coin = models.ForeignKey(Coin)
bought = models.DateTimeField() # date the investment was made
sold = models.DateTimeField() # date the investment was sold
amount = models.DecimalField() # number of coins held
You could then add a property to Portfolio:
class Portfolio(models.Model):
name = models.CharField(max_length=250)
#property
def coins(self):
return Investment.objects.filter(portfolio=self)
In this way you can not only keep track of which portfolio holds which coins, buy also the entire historical positions too.

Model of database for spare parts in django

I'm trying to figure out how to model the database for a spare part app.
Main concern now is the quantity of each part. Some are in pieces, meters, Kg and so on. Some parts needs decimals and some should not have decimals.
This is my raw idea of a basic model.
class Part(models.Model):
name = models.CharField(max_length=550)
class PartNumber(models.Model):
partnumber = models.CharField(max_length=50)
part = models.ManyToManyField(Part, related_name='partnumber')
class Unit(models.Model):
name = models.CharField(max_length=50)
si_unit = models.CharField(max_length=10)
class Stock(models.Model):
quantity = models.DecimalField(max_digits=10, decimal_places=2)
unit = models.ManyToManyField(Unit, related_name='unit')
part = models.ManyToManyField(Part, related_name='part')
Problem is how I should solve the 'quantity' in 'Stock'. Is it better to have two fields? It does not feel right that way either.
I don't think there is a single correct solution, but I'll give my 2 cents.
I would write a model called quantity:
class Quantity(models.Model):
quantity = models.DecimalField(max_digits=10, decimal_places=2)
unit = models.CharField(max_length=50)
If you would like to be able to show stuff in their si_unit, I would consider writing separate model independent code for this or use a library such as python-measurement
If you would like to have queries that need normalised queries, then you could add 2 fields si_quantity and si_unit to Quantity, which would get updated on each Quantity.save()

How can I use Database Relations in Django?

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()

When to use ManyToOne and ManyToMany relationships

The below is a database of colleges, and its ratings. The below is how I thought
Each Class (Batch, ex: Batch of 2009) belongs to a Department
Each Department (ex: department of pharmacy) belongs to a College
As I am particularly concerned about Ratings. I thought to Rate a Batch, there by using a Manager or some Model Method, I can calculate Total Department or College Ratings.
Each Class has Ratings
Note: There may be many ratings by different Users for a single Class. So, I guess Total or Average ratings should be done by a Method!
This is how I so far did
class Rating(models.Model):
positive = models.FloatField(default=0)
negative = models.FloatField(default=0)
class College(models.Model):
name = models.CharField(max_length=200)
website = models.URLField()
class Department(models.Model):
name = models.CharField(max_length=200)
college = models.ForeignKey(College)
class Batch(models.Model):
passout_year = models.IntegerField(max_length=4)
department = models.ForeignKey(Department)
rating = models.ForeignKey(Rating)
This schema has some issues!
Each Batch can only have single rating! However, I am looking for multiple ratings signed by many Users (Though Users model is not integrated yet)
Each Batch belongs to a Department, Each Department belongs to a College. However, we can also think of the relationships in another way
Each College has many Departments, Each Department has many Batches While.. Each Batch has Many Departments (ex: there may be many departments in 2009), and Each Department can be in Many colleges
So, should I use ManyToManyField instead of ForeignKey?
How should I schema should look like?
One of the most essential changes I think are
class Rating(models.Model):
..
..
user = models.ForeignKey(django.contrib.auth.models.User)
class College(models.Model):
..
..
departments = models.ManyToManyField(Department)
class Department(models.Model):
..
college = models.ForeignKey(College)
batches = models.ManyToManyField(Batch)
class Batch(models.Model):
..
department = models.ForeignKey(Department)
rating = models.ManyToMany(Rating)
Is this going to be right? How should it look if if not
Thanks
Here it goes:
from django.contrib.auth.models import User#First import user
lass Rating(models.Model):
..
..
user = models.ForeignKey(User)
class College(models.Model):
..
..
departments = models.ManyToManyField(Department)
class Department(models.Model):
..
college = models.ForeignKey(College)
batches = models.ManyToManyField(Batch)
class Batch(models.Model):
..
department = models.ForeignKey(Department)
rating = models.ManyToMany(Rating)
When you make many to many relationship a bridge entity is automatically created by Django.

Categories