1.

How to create a model in Django?

Answer»

In Django, a model is a special kind of object and it is saved in the database. In the model, you will store information about users, your books, etc. In terms of the database, you can think of a spreadsheet with COLUMNS (fields), and rows (data), as a model.

We are assuming here that the project is CREATED and database connection is set up, and you are in a project folder( or directory where manage.py file is).

To create an application 'dailyblog' execute the command -

$ PYTHON manage.py startapp dailyblog

The new dailyblog directory will be created with the number of files.

Register your dailyblog with the Django project. Open settings.py in the code editor and Update INSTALLED_APPS tuple by adding a line containing 'dailyblog'.

//settings.py INSTALLED_APPS = [     'django.contrib.admin',     'django.contrib.auth',     'django.contrib.contenttypes',     'django.contrib.sessions',     'django.contrib.messages',     'django.contrib.staticfiles',     'dailyblog', ]

In the dailyblog/models.py file, we will define models, that is an object. Here we will define our blog post.

Now open dailyblog/models.py in the code editor, remove all from it and write below code -

//models.py from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model):     author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)     title = models.CharField(max_length=200)     text = models.TextField()     created_date = models.DateTimeField(default=timezone.now)     published_date = models.DateTimeField(blank=True, null=True)     def publish(self):         self.published_date = timezone.now()         self.save()     def __str__(self):         return self.title

Let us see what the above model code means -

Lines starting with 'from' or 'import' add some bits from other files.

  • class Post(models.Model) - This line defines the object, that is our model.
  • Class - is a keyword, used to indicate that we are DEFINING an object.
  • Post - is the model name. It can be anything but should start with upper CASE and we should avoid special characters and whitespace. 
  • models.Model - Django understands this model should be saved in the database.
  • models.ForeignKey - link to another model.
  • models.CharField - defines text with a character field.
  • models.TextField - defines text without limit.
  • models.DateTimeField - date and time field.
  • def publish(self) - def is a function/method and publish is the name of the method. 
  • __str__() - when called __str__(), we will get text string with Post title.


Discussion

No Comment Found