Django: many to many relationship model definition Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Django: many to many relationship model definition without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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!

Answer

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

We are here to answer your question about Django: many to many relationship model definition - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji