InterviewSolution
| 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.titleLet us see what the above model code means - Lines starting with 'from' or 'import' add some bits from other files.
|
|