Django Models - Sloathking/Foolish-Wizardz GitHub Wiki

Django Models

By Brett W

Django models determine what kind of data you are storing in the database, how that data is stored, and what kind of behavior to expect. Django models are also just Python classes, that you define within the models.py file of your application. Our Portfolio application will be composed of 3 primary models: Student, Portfolio, and Project.

Shared class methods

Within each class, there are two methods that we are overriding so that we can control how they behave, the _ _ str _ _ and get_absolute_url methods.

  • _ _ str _ _
  • This method determines what shows up when an object is casted to a string.
  • For Students it returns their name field.
  • For Portfolios and Projects it returns their title field.
#Define default String to return the name for representing the Model object.
def __str__(self):
    return self.name
  • get_absolute_url
  • Overriding this function allows us to dictate the format of the URL that points to this object.
#Returns the URL to access a particular instance of MyModelName.
#if you define this method then Django will automatically
# add a "View on Site" button to the model's record editing screens in the Admin site
def get_absolute_url(self):
    return reverse('student-detail', args=[str(self.id)])

Student Model

This hold information on the students that have created accounts for the Portfolio application, and holds some basic information to identify which student it belongs to, and other information about their degree and major.

Student-UML

class Student(models.Model):
    #List of choices for major value in database, human readable name
    MAJOR = (
        ('CSCI-BS', 'BS in Computer Science'),
        ('CPEN-BS', 'BS in Computer Engineering'),
        ('BIGD-BI', 'BI in Game Design and Development'),
        ('BICS-BI', 'BI in Computer Science'),
        ('BISC-BI', 'BI in Computer Security'),
        ('CSCI-BA', 'BA in Computer Science'),
        ('DASE-BS', 'BS in Data Analytics and Systems Engineering')
    )
    name = models.CharField(max_length=200)
    email = models.CharField("UCCS Email", max_length=200)
    major = models.CharField(max_length=200, choices=MAJOR)

Portfolio Model

Each Student will have a Portfolio that is responsible for storing the projects that Students will be adding to the application.

Portfolio-UML

class Portfolio(models.Model):
    title = models.CharField(max_length=200)
    contact_email = models.CharField("Contact Email", max_length=200)
    is_active = False
    about = models.TextField("About", blank=True)

Project Model

Project-UML

class Project(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField("Project Description")