我建议按照http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany执行此操作
class Material(models.Model):
name = models.CharField(max_length=50)
class Compound(models.Model):
materials = models.ManyToManyField(Material, through='CompoundMaterials')
class CompoundMaterials(models.Model)
Material = models.ForeignKey(Material)
Compound = models.ForeignKey(Compound)
Quantity = models.IntegerField()
我在这是要干嘛?好吧,Django 通常会自动生成一个中间表,用于保存将化合物与元素相关联的键对。在这种情况下,我们自己定义它,但不仅如此,我们还在关系中添加额外的数据,即您所说的数量。
作为示例用法,您可能会这样做:
$ python manage.py shell
from project.app.models import *
oxygen = Material(name="oxygen")
hydrogen = Material(name="hydrogen")
water = Compound(name="water")
oxygen.save()
hydrogen.save()
water.save()
water_chemistry_oxygen = CompoundMaterials(Material=oxygen, Compound=Water, Quantity=1)
water_chemistry_hydrogen = CompoundMaterials(Material=hydrogen, Compound=Water, Quantity=2)
water_chemistry_oxygen.save()
water_chemistry_hydrogen.save()