[PYTHON] How to create a record by pasting a relation to the inheriting source Model in the Model inherited by Django

Overview

How to create a record by pasting a relation to the inheriting source Model in the Model inherited by Django

When pasting a relation to the inheritance source Model, the inheritance source Model may be changed to an unintended value. I will write it including cautions and workarounds!

~~ I was confused by the behavior of Django ~~ I love Django

Environment where operation was confirmed

Python==3.7.4 Django=2.2.3

Conclusion

Give a Model object to the {model name} _ptr field that is implicitly defined during Model inheritance

At this time, if you execute Model.save () or Model.objects.create (), the inherited model may be changed to an unintended value, so use .save_base (raw = True). To do

#Model definition
from django.db import models

    
class Parent(models.Model):
    parent_column = models.CharField(max_length=255)

#Model inheriting ParentModel
class Child(Parent):
    child_column = models.CharField(max_length=255)
    
  

parent = Parent.objects.create(
    parent_column="Text"
)
#Create an inheritance destination model with a relation attached to the created inheritance source model
child = Child(
    parent_ptr=parent,
    child_column="Text"
)
child.save_base(raw=True)

What happens if you inherit Model

If Model is inherited, the field of the inheriting model is also inherited.

In the database, the Child table does not have a parent_column and a foreign key to the Parent table is created

class Child(Parent):
    child_colum = models.CharField(max_length=255)

    #Inherited parent_column also exists
    # parent_colum = models.CharField(max_length=255)

    #Implicitly the inheritance source OneToOneField is also defined
    # parent_ptr = models.OneToOneField(
    #     Parent,
    #     parent_link=True
    # )

[Caution] In order not to affect the inherited Model

As a note

The value of Parent.parent_column will be empty if you do the following:


parent = Parent.objects.create(parent_column="Text")
Child.objects.create(
    parent_ptr=parent,
    child_column="Text"
)

""Returns
print(Parent.objects.get(pk=parent.pk).parent_column)

this is, Occurs because parent_link = True is defined in the parent_ptr field of ChildModel

As a result, the parent of parent_ptr = parent is updated at the time of create. ChildModel also defines an inherited parent_column field

By creating without specifying a value in this field, it will be updated on the parent side. To avoid this

By using Model.save_base (raw = True), you can insert the inherited model without updating the inherited model.

Recommended Posts

How to create a record by pasting a relation to the inheriting source Model in the Model inherited by Django
How to create a Rest Api in Django
Read the Python-Markdown source: How to create a parser
How to generate a query using the IN operator in Django
How to sort by specifying a column in the Python Numpy array.
How to create a JSON file in Python
How to uniquely identify the source of access in the Django Generic Class View
How to count the number of elements in Django and output to a template
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
How to get the "name" of a field whose value is limited by the choice attribute in Django's model
How to get multiple model objects randomly in Django
How to create a submenu with the [Blender] plugin
How to use the model learned in Lobe in Python
How to reference static files in a Django project
How to write custom validations in the Django REST Framework
How to use the __call__ method in a Python class
A story that makes it easier to see Model debugging in the Django + SQLAlchemy environment
How to get the last (last) value in a list in Python
Create a new list by combining duplicate elements in the list
In Django, how to abbreviate the long displayed string as ....
[Django] What to do if the model you want to create has a large number of fields
How to return the data contained in django model in json format and map it on leaflet
[sh] How to store the command execution result in a variable
How to determine the existence of a selenium element in Python
How to get all the possible values in a regular expression
How to check the memory size of a variable in Python
How to create a heatmap with an arbitrary domain in Python
[Introduction to Python] How to use the in operator in a for statement?
How to check the memory size of a dictionary in Python
How to get the vertex coordinates of a feature in ArcPy
How to create a large amount of test data in MySQL? ??
How to deploy a Django app on heroku in just 5 minutes
Create a function to get the contents of the database in Go
Create a REST API to operate dynamodb with the Django REST Framework
Steps to create a Django project
How to create a Conda package
How to create a virtual bridge
How to reflect CSS in Django
How to create a Dockerfile (basic)
How to create a config file
Create a LINE Bot in Django
A note that you want to manually decorate the parameters passed in the Django template form item by item
How to make a model for object detection using YOLO in 3 hours
How to specify a .ui file in the dialog / widget GUI in PySide
[NNabla] How to add a quantization layer to the middle layer of a trained model
Added a function to register desired shifts in the Django shift table
How to get a namespaced view name from a URL (path_info) in Django
How to create a wrapper that preserves the signature of the function to wrap
[Development environment] How to create a data set close to the production DB
Create a record with attachments in KINTONE using the Python requests module
What is the fastest way to create a reverse dictionary in python?
How to create a git clone folder
How to check the version of Django
How to delete expired sessions in Django
Create a model for your Django schedule
How to get a stacktrace in python
How to create a repository from media
How to do Server-Sent Events in Django
How to convert DateTimeField format in Django
Implement a Custom User Model in Django
How to pass the execution result of a shell command in a list in Python