Working with Django Models

Defining a model

To define the models for your app, modify the file that was created in your app’s folder. The str() method tells Django how to represent data objects based on this model.

from django.db import models

"""A topic the user is learning about."""
class Topic(models.Model):
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(

    def str(self):
         return self.text

Defining a model with a foreign key

class Entry(models.Model):
    """Learning log entries for a topic."""
    topic = models.ForeignKey(Topic)
    text = models.TextField()
    date_added = models.DateTimeField(
    def str(self):
        return self.text[:50] + "…"

Activating a model

To use a model the app must be added to the tuple INSTALLED_APPS, which is stored in the project’s file

    # My apps

Migrating the database

The database needs to be modified to store the kind of data that the model represents.

python makemigrations learning_logs
python migrate

Creating a superuser

A superuser is a user account that has access to all aspects of the project.

python createsuperuser

Registering a model

You can register your models with Django’s admin site, which
makes it easier to work with the data in your project. To do this,
modify the app’s file.

from django.contrib import admin
from learning_logs.models import Topic

Leave a Reply

Your email address will not be published. Required fields are marked *