Reputation: 3802
I am creating a simple game database and I am having some problems.
There are 2 models: Material and Building.
class Material(Model):
type = CharField(max_length=30)
class Building(Model):
cost = M2M(?)
input = M2M(?)
output = M2M(?)
In the material model, material names are held (Wood, Stone, Iron, Plank, Fish, Food etc.). Building should have a bit more fields, however, I encounter difficulties with these only. Imagine something like "The Settlers" game. The building demands 3 pieces of stone to be build (cost) and it takes 2 pieces of wood (input) to produce 1 plank (output).
How can I make such structure where I could specify the amount of material and easily modify it if necessary.
I have already tried to use through argument, however, it did not let me have 3 or more occurrences in the model.
Upvotes: 1
Views: 229
Reputation: 28637
perhaps your through table could have a quantity
field?
edit:
ah, i see. this is a limitation due to the way through tables work. A through table only has references to the two models it's joining together, but can't know which fields on said models are defining the m2m relationship. So each through table may only be used for one relation. However, with some abstract subclassing we can keep the code fairly clean:
class BuildingMaterialBase(models.Model):
material = models.ForeignKey('Material')
building = models.ForeignKey('Building')
quantity = models.IntegerField()
class Meta:
abstract = True
class BuildingMaterialIn(BuildingMaterialBase):
pass
class BuildingMaterialOut(BuildingMaterialBase):
pass
class Building(models.Model):
in_ = models.ManyToManyField(Material, through=BuildingMaterialIn)
out_ = models.ManyToManyField(Material, through=BuildingMaterialOut)
Upvotes: 1