[PYTHON] When you want to register Django's initial data with relationships

The method of setting initial data in Django is a bit quirky. I will write what I am a little addicted to.

Initialization of data including ForeignKey

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"
    }
  }
]

Recommended Posts

When you want to register Django's initial data with relationships
Settings when you want to run python-mecab with travis
When you want to filter with Django REST framework
Solution when you want to use cv_bridge with python3 (virtualenv)
Use aggdraw when you want to draw beautifully with pillow
I know? Data analysis using Python or things you want to use when you want with numpy
If you want to use field names with hyphens when updating firestore data in python
If you want to become a data scientist, start with Kaggle
When you want to print to standard output with print while testing with pytest
When you want to send an object with requests using flask
When you want to adjust the axis scale interval with APLpy
When you want to use it as it is when using it with lambda memo
Gist repository to use when you want to try a little with ansible
When you want to replace a column with a missing value (NaN) column by column
Memorandum of means when you want to make machine learning with 50 images
I want to knock 100 data sciences with Colaboratory
When you want to update the chrome driver.
I want to start over with Django's Migrate
Personal best practice template to use when you want to make MVP with Flask
[OpenCV] When you want to check if it is read properly with imread
When you want to play a game via Proxy
Things to do when you start developing with Django
When you want to plt.save in a for statement
When the variable you want to superscript with matplotlib is two or more characters
Knowledge you need to know when programming competitive programming with Python2
I want to be able to analyze data with Python (Part 1)
Useful operation when you want to solve all problems in multiple programming languages with Codewars
I want to be able to analyze data with Python (Part 4)
I want to be able to analyze data with Python (Part 2)
When you want to use python2.x on modern Gentoo Linux
When you want to hit a UNIX command on Python
[Subprocess] When you want to execute another Python program in Python code
Don't write Python if you want to speed it up with Python
When it is troublesome to copy what you built with vue
When you want to keep the Sphinx documentation theme as usual
When you want to save the result of the callback function somewhere
[TensorFlow] If you want to run TensorBoard, install it with pip
When you want to sort a multidimensional list by multiple lines
Nice to meet you with python
How to deal with imbalanced data
How to deal with imbalanced data
Key operations you want to know
How to Data Augmentation with PyTorch
I want to do ○○ with Pandas
I want to debug with Python
I want to get angry with my mom when my memory is tight
If you want to include awsebcli with CircleCI, specify the python version
Python Note: When you want to know the attributes of an object
When you want to change the HTTP headers of Flask's test client
Wrapper when you want to output utf-8 + ansi color on Windows console
Ansible role to prevent the initial confirmation message when connecting with SSH
Tips (data structure) that you should know when programming competitive programming with Python2
How to use ManyToManyField with Django's Admin
Send data to DRF API with Vue.js
Convert FX 1-minute data to 5-minute data with Python
I want to analyze logs with Python
I want to play with aws with python
Try converting to tidy data with pandas
When you want a long line break
Let's summarize what you want to do.
How to read problem data with paiza