I am trying to figure out how to define a one-to-many relationship between two models. The difficulty here is that I do not want to touch one of the models and therefore can not use the usual ForeignKey (Many-to-one).
There are many question on this topic but they all either talk about how to do the lookup (reverse ForeignKey lookup) or they suggest to just add a Foreign Key to one side. Here is a similar question. I will use the same code example. This is what I am looking for:
class Dude(models.Model):
numbers = models.OneToManyField('PhoneNumber')
class PhoneNumber(models.Model):
number = models.CharField()
Usually I would go ahead and just add a Foreign Key to PhoneNumber as suggested in many answers:
class PhoneNumber(models.Model):
dude = models.ForeignKey(Dude, related_name='numbers')
But in my situation I would like to not touch the PhoneNumber model and therefore define something on the Dude model.
The reason for this is that I am defining a model describing a special circumstance which is rarely used. If I used a ForeignKey on the (PhoneNumber) model I would have 99.9% of all instances leave this field blank. I do not really like the idea to have a field which is always blank - maybe this is my problem.
A possible work-around is to define a many-to-many field and then add some logic actually preventing 'many' on one side and enforcing that the other side is not empty.
I hope I could describe my problem clearly.
Question: Is there some way to define a one-to-many relationship? Is there a better solution with a different approach for my problem?
P.S. The only hit on this I get from the django docs is a field attribute one_to_many which, I am guessing, is used for the lookup.