Django Models | Set – 1
Prerequisites : Django Creating apps
According to Django Models, A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.
- Each model is a Python class that subclasses django.db.models.Model.
- Each attribute of the model represents a database field.
- With all of this, Django gives you an automatically-generated database-access API.
Django models are used as a structure to define fields and their types which will be saved in the database. Whatever changes we want to make in the database and want to store them in the database permanently are done using Django Models. A table for a phone in the database can be imagined as:
Create table in database using Django –
We need to create a new app named product so that we can define all properties of phone described in the above-provided image. Open your terminal and run following command:
python manage.py startapp product
Now, our directory will be:
After creating the app, don’t forget to mention it in
geeks_site/settings.py under INSTALLED_APPS.
Also, register it with admin by adding following line of code to product/admin.py. By registering it with admin, you make sure that admin of the site will be aware that new table schema for database has been prepared.
Now, navigate to product/models.py. You will see a file with following lines:
We use a python class to define models which inherit parent class named Model defined in django.db.models package.
Add the following lines of code to this file: