The process for adding models in Django
# project_name/app_name/models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
def __str__(self):
return self.name
# changing the pluralization and adding an ordering
class Meta:
ordering = ["name"]
verbose_name_plural = "categories"
# A virtual attribute
def popular(self):
return self.likes >= 100
popular.short_description = 'Top Category?'
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __str__(self):
return '%s id: %s' % (self.title, self.id)# project_name/app_name/models.py
from django.contrib import admin
from rango.models import Category, Page
# class to customize page view in /admin (note PageAdmin in arguments on line 15)
class PageAdmin(admin.ModelAdmin):
# controls how index of all pages are shown
list_display = ('title', 'category', 'views')
list_filter = ('category')
# controls how view of each page is shown
fieldsets = [
('Category', {'fields': ['category']}),
('Page information', {'fields': ['title', 'views'], 'classes': ['collapse']}),
]
# register models to make them accessible via the /admin interface
admin.site.register(Category)
admin.site.register(Page, PageAdmin)
models.py file.admin.py to include and register your new model(s).$ python manage.py makemigrations$ python manage.py migrate. This will create the necessary infrastructure within the database for your new model(s).