Django - Foreign Keys in Fixtures

2019-04-19 11:45发布

问题:

I have a fixture of "User" objects (just the default Django auth ones), and am trying to create a fixture of "Profile" objects. Each profile has a one-to-one relation to a user object, and defines some more custom stuff for that user.

As far as I can tell, the normal way of dealing with foreign keys in a fixture is to just hardcode the primary key of the foreign object into the fixture. Is there a way to avoid doing that?

Basically, I'm trying to have something like '"user":username' in the fixture rather than '"user":pk'.

Is there any way to do this?

回答1:

You're looking for "Natural Keys" https://docs.djangoproject.com/en/dev/topics/serialization/#natural-keys