For example,
|
Syntax
field_name = models.UUIDField ( ** options )
Django UUIDField Model Explained
Illustration of a UUIDField using an example. Consider a project named pythonengineering
that has an application named geeks
.
Refer to the following articles to check how to create a project and an app in Django.
Enter the following code into the models.py
file of the geeks application.
|
|
Now when we run makemigrations
from the terminal,
Python manage.py makemigrations
In the geeks
directory b A new folder named migrations will be created with a file named 0001_initial.py
|
So geeks_field
geeks_field is generated when you run makemigrations for the project. This is a field to store an instance of a UUID in python.
How to use a UUIDField?
UUID, a universally unique identifier, is a python library that helps generate random 128-bit objects as identifiers. To learn more about UUIDs, visit # model import
# from geek app
from
geeks.models
import
GeeksModel
# import uuid
import
uuid
# instantiate
# UUID object
test
=
uuid.uuid4 ()
# instantiate
# GeeksMo del
geek_object
=
GeeksModel.objects. create (geeks_field
=
test)
geek_object .save ()
Now let’s check it out on the admin server. We have created a GeeksModel instance
Field options
Field parameters — they are arguments given to each field to apply some constraint or to convey a particular characteristic to a particular field. For example, adding the null = True
argument to the UUIDField will allow it to store empty values for that table in a relational database.
Here are the options and attributes that UUIDField can use.
Field Options | Description |
---|---|
Null | If True , Django will store empty values as NULL in the database. Default is False. |
Blank | If True , the field is allowed to be blank ... Default is False. |
Choices | An iterable (eg, a list or tuple) of 2-tuples to use as choices for this field. |
Default | The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created. |
help_text | Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. |
primary_key | If True, this field is the primary key for the model . |
Unique | If True, this field must be unique throughout the table. |