I know what ForeignKeys and OneToOneFields are, as well as ManyToManyField, how they work, and when to use them. However, I am working with a project, whose Many part of the relation cannot be modified. So, suppose I want to let a user have many phone numbers, I would normally do this:
# my_app/models.py
from django.db import models
class User(Model):
...
class PhoneNumber(models.Model):
user = models.ForeignKey(User)
The problem I have is that my PhoneNumber
model equivalent is from a third-party package, already populated with records, and not subclassed in my own app. That is
# third_party_django_package/models.py
from django.db import models
class PhoneNumber(models.Model):
# This cannot change
# my_app/models.py
from django.db import models
from third_party_django_package.models import PhoneNumber
class User(Model):
# These do not work -- a user can have more than one phone number
phone_number = models.ForeignKey(PhoneNumber)
phone_number = models.OneToOneField(PhoneNumber)
# This is close, but I want a phone number to belong to only one User
phone_numbers = models.ManyToManyField(PhoneNumber, related_name=...)
def clean(self):
# Validating the M2M relation costs extra queries, is slow, and
# is prone to race conditions
This is all pseudocode.
Without using yet another third-party package that accesses Django's internal members, which makes the project even less forwards-compatible, what options do I have left to achieve a proper OneToManyField with the correct schema-level constraints?