Working with Django Models

Defining a model

To define the models for your app, modify the file models.py 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(
    auto_now_add=True)

    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(
    auto_now_add=True)
    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 settings.py file

INSTALLED_APPS = (
    --snip--
    'django.contrib.staticfiles',
    # My apps
    'learning_logs',
)

Migrating the database

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

python manage.py makemigrations learning_logs
python manage.py migrate

Creating a superuser

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

python manage.py 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 admin.py file.

from django.contrib import admin
from learning_logs.models import Topic
admin.site.register(Topic)

Leave a Reply

Your email address will not be published.