Adding Database Models¶
If your app introduces a new type of object in Nautobot, you'll probably want to create a Django model for it. A model is essentially a Python representation of a database table, with attributes that represent individual columns. Model instances can be created, manipulated, and deleted using queries. Models must be defined within a file named
It is highly recommended to have app models inherit from at least
nautobot.apps.models.BaseModel which provides base functionality and convenience methods common to all models.
For more advanced usage, you may want to instead inherit from one of Nautobot's "generic" models derived from
nautobot.apps.models.PrimaryModel. The inherent capabilities provided by inheriting from these various parent models differ as follows:
|UUID primary key||❌||✅||✅||✅|
Below is an example
models.py file containing a basic model with two character fields:
# models.py from django.db import models from nautobot.apps.models import BaseModel class Animal(BaseModel): """Base model for animals.""" name = models.CharField(max_length=50) sound = models.CharField(max_length=50) def __str__(self): return self.name class Meta: unique_together = [["name", "sound"]]
Once you have defined the model(s) for your app, you'll need to create the database schema migrations. A migration file is essentially a set of instructions for manipulating the database to support your new model, or to alter existing models.
Creating migrations can be done automatically using the
nautobot-server makemigrations <app_name> management command, where
<app_name> is the name of the Python package for your app (e.g.
An app must be installed before it can be used with Django management commands. If you skipped this step above, run
poetry install from the app's root directory.
Next, apply the migration to the database with the
nautobot-server migrate <app_name> command:
For more background on schema migrations, see the Django documentation.