Django – create your first model
In Django, a “model” is a Python class which turns database entities into objects. You create the class, and then use it to build the database tables and to add/edit/delete database entities. Here is a brief example
Models are part of “apps”, and apps are part of a project. For instance, a book store system may have an Inventory app, with books, shelves, etc, and a Finance app, with sales, purchases, etc
- Create a new app
- Start the virtual environment
- Switch to the project folder
- (DjangoTest) python manage.py startapp books
- If all is well, no message will be shown
- In your favourite editor, open <dev root>Projects/HelloWorldDjango/books/models.py
- Add the following at the end:class Author (models.Model):
first_name = models.CharField(max_length = 30)
last_name = models.CharField(max_length = 40)class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
- Add the following at the end:class Author (models.Model):
- Add this to the installed apps:
- In settings.py, at the end of the INSTALLED_APPS list, add “books, “
- Test this: python manage.py validate. You should see: no issues
- Set up the minimum required (INSTALLED_APPS) database: python manage.py migrate
- Create additional migrations for your new books app: python manage.py makemigrations book
- Apply these migrations to the database: python manage.py migrate