Make any key the primary key in Django's model

In Django you have to specify nothing in the model The primary key name is id, the type is integer, and it is generated as a serial number from 1.

Here, as the primary key of the model An example of using UUID (Universally Unique Identifier) is shown.

model.py


from django.db import models
import uuid

class Sample(models.Model):
	sampleId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

The point is the ** primary_key = True ** part below, It is clearly stated here that sampleId is the primary key.

sampleId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

I want the model object to be assigned automatically when it is created, so Specify ** default = uuid.uuid4 **.

In addition, if you change the primary key without much thought Specify ** editable = False ** because DB integrity is likely to be broken (There is a high possibility that it will be difficult to move here ...)

Recommended Posts

Make any key the primary key in Django's model
Link the list_display item in Django's Model Admin
To make sure that the specified key is in the specified bucket in Boto 3
Make the line breaks visible in journalctrl
Make the SIR model calculation program GUI
Benefits of using slugfield in Django's model
Install the Python module in any directory
If you specify a foreign key in Django's model change, you need to specify on_delete.
How to change the appearance of unselected Foreign Key fields in Django's ModelForm
Make a copy of the list in Python
Search for yourself from methods in Django's model
Make progress of dd visible in the progress bar
Customize the model page on Django's admin screen
Make inferences using scikit-learn's trained model in PySpark
Specify the lighting Model of SCN Material in Pythonista
Count the number of parameters in the deep learning model
How to use the exists clause in Django's queryset
Make the model a string on a Django HTML template
Access Github by specifying the SSH key in GitPython
How to use the model learned in Lobe in Python