So a little overview of Django models and its’ instances. Django model is basically like a database table. To create one you need to change models.py and admin.py file. In models.py you declare your models and in admin.py you import the created models to generate tables in admin interface. To start using models you need to make “makemigrations” and “migrate” in console. If you haven’t created a superuser yet, you also need to do that to access Django admin panel.

Models.py:

  # Firstly you need to import models from Django database.
  from django.db import models

  # Then for each model define a Class:
  class ModelName(models.Model):
      to something..
      # Then inside the class define fields (which is basically column of the database):
      # Easiest is the charfield, which takes text as input:
      name = models.CharField(max_length=200)

Now I’ll go over different models instances I have used:

1) Foreign Key - ForeignKey can be a second model or a user

  author = models.ForeignKey('auth.User')
  campaign = models.ForeignKey(FirstModelName, blank=True, null=True)

2) Int and char and text - number; short text; long text. Default is the value that is saved if you don’t change anything, can also be default = ‘’”

  name = models.CharField(max_length=200)
  description = models.TextField()
  number = models.IntegerField(default="25")

3) File upload:

  file = models.FileField(upload_to='documents/', default="")

4) Options: choose one

  CHOICES = (
    ('A', 'Description of A'),
    ('B', 'Description of B'),
    ('C', 'Description of C')
  )
  dropdown = models.CharField(choices=CHOICES, max_length=50, default="")

5) Checkbox options:

  checkboxes = MultiSelectField(choices=CHOICES, default="")

This is not a default field, needs to be installed in console: pip install django-multiselectfield

6) datefield:

  from django.utils import timezone
  created_date = models.DateField(default=timezone.now)

I also have methods defined in my class.

  def publish(self):
    self.published_date = timezone.now()
    self.save()
    def __str__(self):
    return self.name

admin.py file:

  from .models import FirstModel, SecondModel
  # have to register each model on separate row
  admin.site.register(FirstModel)
  admin.site.register(SecondModel)

In console: (Windows) python manage.py makemigrations python manage.py migrate python manage.py createsuperuser username: e-mail: password: python manage.py runserver

In browser: http://127.0.0.1:8000/admin/ Log in and start adding data.


Django models documentation