Reputation: 208
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!
Upvotes: 0
Views: 173
Reputation: 5193
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
Upvotes: 2