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

  1. Create a new app
    1. Start the virtual environment
    2. Switch to the project folder
    3. (DjangoTest) python manage.py startapp books
    4. If all is well, no message will be shown
  2. In your favourite editor, open <dev root>Projects/HelloWorldDjango/books/models.py
    1. 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)

  3. Add this to the installed apps:
    1. In settings.py, at the end of the INSTALLED_APPS list, add “books, “
  4. Test this: python manage.py validate. You should see: no issues
  5. Set up the minimum required (INSTALLED_APPS) database: python manage.py migrate
  6. Create additional migrations for your new books app: python manage.py makemigrations book
  7. Apply these migrations to the database: python manage.py migrate

 

You may also like...