Django Models
Learn about Django Models
What Are Models?
In Django, a model is a Python class that represents a database table. Each attribute of the class maps to a column in the table. Django's ORM (Object-Relational Mapper) handles all the SQL behind the scenes, so you interact with your database using Python code instead of writing raw SQL queries.
Designing the Contact Model
Open the contacts/models.py file and define the Contact model. Each contact will have a first name, last name, email address, phone number, and a profile photo. The model should also include a created_at timestamp that is automatically set when a new contact is created.
Field Types
- CharField — For short text like names, with a max_length parameter
- EmailField — A CharField that validates email format
- ImageField — For file uploads, stores the path to the uploaded image
- DateTimeField — For dates and times, with auto_now_add for creation timestamps
Adding a String Representation
Define a __str__ method on the model that returns a human-readable string, such as the contact's full name. This will be displayed in the Django admin panel and when you print a contact object in the shell.
Making Migrations
Every time you create or change a model, you need to generate a migration file and apply it to the database:
python manage.py makemigrations
python manage.py migrate
This creates the actual database table based on your model definition. Django uses SQLite by default, which requires no additional setup.
Registering the Model in Admin
Open contacts/admin.py and register the Contact model. Then create a superuser account so you can log into the admin at /admin and manually add a few test contacts:
python manage.py createsuperuser