Django Tutorial - Video 2 - Models and the Admin

This tutorial walks through an introduction to creating models and how to plan out the database. It covers adding objects with the built in admin interface, defining and entering ForeignKey relationships, and a brief introduction to the django interactive shell used for querying models in real time. We also look at subclassing the admin interface to customize the way the built in administration backend works.


beer/models.py

from django.db import models

BEER_CHOICES = (
        ('D', 'Domestic'),
        ('I', 'Import'),
)

class Beer(models.Model):
        name            = models.CharField(max_length=200)
        slug            = models.SlugField(unique=True)
        brewery         = models.ForeignKey('Brewery')
        locality        = models.CharField(max_length=1, choices=BEER_CHOICES)
        description     = models.TextField(blank=True)

        def __unicode__(self):
                return self.name

class Brewery(models.Model):
        name            = models.CharField(max_length=200)
        slug            = models.SlugField(unique=True)
        description     = models.TextField(blank=True)

        def __unicode__(self):
                return self.name
	

Add 'beer' to INSTALLED_APPS in settings.py

beer/admin.py

from django.contrib import admin
from beer.models import Beer, Brewery

class BeerAdmin(admin.ModelAdmin):
        prepopulated_fields = {'slug': ('name',)}
        list_display = ('name', 'brewery', 'locality')
        search_fields = ['name']

class BreweryAdmin(admin.ModelAdmin):
        prepopulated_fields = {'slug': ('name',)}

admin.site.register(Beer, BeerAdmin)
admin.site.register(Brewery, BreweryAdmin)