class Bank(models.Model):
name = models.Charfield()
money = models.IntegerField()
class StockShares(models.Model):
name = models.Charfield()
price = models.Charfield()
现在要建立一种关系我知道我必须添加
stock = models.ManyToManyField(StockShares)
但是,如何添加仅在购买或销售时才存在的关系属性?
我在想也许我可以这样做:
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
这是我在没有使用django和数据库管理器
的情况下的规范有没有办法在django中实现这一点,而不用中间类来处理这种关系?或者我正在做我的好事,这就是django必须要做的事情
pd:英语不是我在这里尽我所能的第一语言
提前感谢您的回答!
答案 0 :(得分:2)
您正在寻找Extra fields on many-to-many relationships
您的代码应如下所示:
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()
也许数量应该计算字段