Django 4 Week Challenge: Models
So my Django 4 week challenge is officially in progress.
For the last two days I have been looking into Models and how they work, at first they were a bit confusing but I’ve started watching this Youtube video to help me learn Django.
I have a basic Django project running at the moment, it has the main project as well as a ‘Product’ project just for making test models.
I’ve learned that the process to create a model goes as follows.
First you create a class under the models.py file;
class Product(modles.Model): title = models.TextField() description = models.TextField() price = models.TextField()
Then that model needs to be listed under the installed apps section in the settings.py file under the main project;
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #own apps 'products', ]
Then you need to add the new model to the database;
py .\manage.py makemigrations Migrations for 'products': products\migrations\0001_initial.py - Create model Product py .\manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, products, sessions Running migrations: Applying products.0001_initial... OK
The model is now stored in the database, but if you want to access it via the admin page you will need to register it under the admin.py file;
from django.contrib import admin # Register your models here. from .models import Product admin.site.register(Product)
Now the product model can be seen.
I haven’t touched Python for a few months now, so I’m also having to remember how to do a few things as I go along, but it’s no drama.