The method of setting initial data in Django is a bit quirky. I will write what I am a little addicted to.
A tutorial that tells you to write the Primary Key of an externally referenced field. .. Unfortunately, I couldn't do that because I had changed the Primary Key to uuid.
By the way, for reference, I was doing something like this.
models.py
class UUIDpk(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4,)
class Meta:
abstract = True
parent.json
[
{
"model": "app.ParentModel",
"fields": {
"name": "Dog"
}
}
]
children.json
[
{
"model": "app.ChildrenModel",
"fields": {
"parent": "It's a bit unreasonable to specify with uuid.."
"name": "Chihuahua"
}
}
]
Natural key
However, Django is an excellent FW, so it's okay ...! You can set search conditions for relations separately from the Primary Key. Official Documents
models.py
class Parent(UUIDpk):
class ParentManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
#Behave and unique=Let's set it to True.
name = models.CharField(max_length=50, unique=True)
objects = ParentManager()
In the above example, only the name field is set to Natural Key, but of course it is okay to have more than one.
Change the json file registered with loaddata as follows.
parent.json
[
{
"model": "app.ParentModel",
"fields": {
"name": "Dog"
}
}
]
children.json
[
{
"model": "app.ChildrenModel",
"fields": {
"parent": ["Dog"]
"name": "Chihuahua"
}
}
]