We have a problem in our schema design for our database that I would like to figure out the cleanest way to solve. The three models are defined in these simplified Django model classes:
class Animal(Model):
name = CharField()
infusion_rate = FloatField()
infusate = ForeignKey(Infusate) # but with specific tracer concentrations?
class Infusate(Model):
name = CharField()
tracers = ManyToManyForeignKey(Tracer)
class Tracer(Model):
name = CharField()
Currently, we have a through
model for the Infusate
:Tracer
M:M relationship that adds a concentration
float field:
class InfusateTracer(Model):
infusate = ForeignKey(Infusate)
tracer = ForeignKey(Tracer)
concentration = FloatField()
but we need to link the Animal model to a single infusate, but with specific concentrations for each of its multiple tracers. In other words, how do I relate an animal to a single infusate, but multiple tracers with specific concentrations belonging to that one infusate?
I was thinking that I could add a field to InfusateTracer
and have Animal
link to that instead. Let’s call it animal
, so:
class InfusateTracer(Model):
infusate = ForeignKey(Infusate)
tracer = ForeignKey(Tracer)
concentration = FloatField()
animal = IntegerField()
but how do I enforce that the relationship between infusate
and animal
fields in the InfusateTracer
model is M:1 (i.e. InfusateTracer.animal
never co-occurs with multiple different InfusateTracer.infusate
values (but multiple InfusateTracer.tracer
values))? Is there some sort of unique constraint I can use to enforce that?
From a different angle, I could create an AnimalTracer linking/through model, but then I would have the same difficulty of retrieving a single unique infusate name associated with the animal.
Trying to figure out the most elegant solution that maintains data integrity is melting my brain.