To avoid the XY problem, I will describe my problem and my attempted solution separately.
My problem
I have an Appointment
model which I want to write fixtures for. There is a one-to-many mapping from the Django User
model to the Appointment
model (every appointment has only one client, but a client can have multiple appointments).
I know I can hard code the primary key for the User
s in my appointment fixtures, but would be a brittle solution. Hard coding the foreign keys also compromises the readability of my fixtures.
My attempted solution
I looked at this question, which has an answer linking to Django documentation for natural keys. However, I ran into a problem attempting to use this approach.
I believed I could create a proxy model for the User
model, so I could create a custom Manager
for natural keys. Here is my proxy model:
class UserProxy(User):
objects = UserManager # The UserManager class's code is omitted
class Meta:
proxy = True
unique_together = [['username']]
(If the UserManager
class's code is relevant, please let me know in a comment, and I will add it.)
However, when I run manage.py makemigrations
, I get this error:
ERRORS:
accounts.UserProxy: (models.E016) 'unique_together' refers to field 'username' which is not local to model 'UserProxy'.
HINT: This issue may be caused by multi-table inheritance.
I understand this error message: the username
field belongs to the User
model, not to the UserProxy
model.
My questions
- Is my proxy model approach a good approach? If it is not, what should I do instead?
- If my proxy model approach is a good approach, how can I correctly refer to the
User
model'susername
field in myunique_together
list?