Blog | CoWhite Softwarehttp://django.cowhite.com/blog/2017-08-03T09:53:50+00:00BlogModels and Migrations2017-08-03T09:53:50+00:00srinath/blog/author/srinath/http://django.cowhite.com/blog/models-migrations-and-django-admin/<h3>Setting up Database</h3>
<p>
Before we start with models let's understand how to setup database to work with Django. Django comes pre bundled and ready to work with SQLite database, which for development and for very small lightweight websites would be enough to wor with, but if the scale of the website or the user-base of the website is even moderately high, SQLite is definitely not enough.
</p>
<p><br />
<p>
Other than SQLite Django can work with the following Databases:<br />
• MySQL<br />
• Postgres<br />
• Oracle<br />
</p><br />
<p>
Let's see how to setup the database for each of the above backends.
</p><br /><br />
<h4>SQLite</h4>
<p>
The settings for any database is registered in the <strong>settings.py</strong> file in <em>myprojectname/myprojectname/</em> directory. We register them by listing the settings for the database as a Python dictionary. It is a nested dictionary whose contents map a database alias to a dictionary containing the options for an individual database.
</p><br />
<p>
For the SQLite backend we have the following setting, which is probably the simplest:</p>
<div class="codehilite"><pre>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'awesomedb',
}
}
</pre></div>
<p></p><br />
<p>
Please note that the dictionary is assigned to a variable named <code>DATABASES</code>. It should be named the same. Also the <code>'NAME'</code> property specifies the SQLite database filename that should be used to store the backend data.
</p><br /><br />
<h4>MySQL, Postgres, Oracle</h4>
<p>
When connecting to other database backends, such as MySQL, Oracle, or PostgreSQL, additional connection parameters will be required, viz, database username and password, database host URL and port etc.
</p><br />
<p>
Also unlike SQLite database, we need to install certain dependencies for Django to be able to connect to these backends.<br />
• If you’re using PostgreSQL, you’ll need the <a href="http://initd.org/psycopg/">psycopg2</a> package (2.5.4 or higher).<br />
• If you’re using MySQL, you’ll need a DB API driver like <a href="https://pypi.python.org/pypi/mysqlclient">mysqlclient</a>. Also MySQL version should be 5.5 or higher.
• If you’re using Oracle (v11.2 or higher supported), you’ll need a copy of <a href="https://oracle.github.io/python-cx_Oracle/">cx_Oracle</a> (version 5.2 or higher).</p>
<p></p><br />
<p>
Given below is the example for connecting a <strong>PostGres</strong>:
</p><br />
<p></p>
<div class="codehilite"><pre>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'awesomedb',
'USER': 'awesomedbuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
</pre></div>
<p></p><br />
<p>
For connecting to other Databases, edit the value for <code>'ENGINE'</code> as follows:<br />
</p><br />
<table>
<tbody>
<tr>
<th style="padding-left: 5px; padding-right: 5px;border-bottom: 1px solid;">
Database
</th>
<th style="padding-left: 5px; padding-right: 5px;border-bottom: 1px solid;">
<code>'ENGINE'</code> value
</th>
</tr>
<tr>
<td style="padding-left: 5px; padding-right: 5px;">
MySQL
</td>
<td style="padding-left: 5px; padding-right: 5px;">
<code>'django.db.backends.mysql'</code>
</td>
</tr>
<tr>
<td style="padding-left: 5px; padding-right: 5px;">
ORACLE
</td>
<td style="padding-left: 5px; padding-right: 5px;">
<code>'django.db.backends.oracle'</code>
</td>
</tr>
</tbody>
</table><br /><br />
<h4>Timezone Setting</h4>
<p>
While you are setting up the <strong>myprojectname/settings.py</strong>, set <code>TIME_ZONE</code> to your timezone. <code>TIME_ZONE</code> should be a string representing the time zone. Click here for the list of <a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">timezones</a>.
</p><br /><br />
<h4>Installed apps</h4>
<p>
Note the <code>'INSTALLED_APPS'</code> setting at the top of the file. This holds the names of all the Django applications activated in this particular Django project. As we have discussed above, apps can be used in multiple projects and can also be packaged and distributed for use by others in their projects.
</p><br />
<p>
The default <code>'INSTALLED_APPS'</code> contain the following apps. These apps are prepackaged apps that come with Django.<br />
• <code>django.contrib.admin</code> -> The admin site. We will look in to it ahead in this blog.<br />
• <code>django.contrib.auth</code> -> The authentication system for Django.<br />
• <code>django.contrib.contenttypes</code> -> A framework for content types.<br />
• <code>django.contrib.sessions</code> -> The sessions framework.<br />
• <code>django.contrib.staticfiles</code> -> Framework for managing static assets files.
</p><br />
<p>
<strong>Important Note</strong>: Some of the above applications make use of database. And right now although you may have setup the SQL server (no setting up needed for SQLite.), the database tables needed for these applications aren't migrated into them. So lets migrate them first. To do that, run the following command:
</p><br />
<p>
<pre>
<code>
python manage.py migrate
</code>
</pre>
</p><br /><br />
<h3>Creating a Model</h3>
<p>
Models are nothing but database layouts with additional metadata. Let's see how to create our first Models in Django.
</p><br />
<p>
In our simple poll app, we’ll create two models: Question and Choice. A Question has a question and a publication date. A Choice has two fields: the text of the choice and a vote tally. Each Choice is associated with a Question.
</p><br />
<p>
These concepts are represented by simple Python classes. Edit the polls/models.py file so it looks like this:
</p><br />
<p></p>
<div class="codehilite"><pre><span class="c"># Python Code</span>
<span class="c"># polls/models.py</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="k">class</span> <span class="nc">Question</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
<span class="n">question_text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
<span class="n">pub_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="s">'date published'</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Choice</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
<span class="n">question</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
<span class="n">choice_text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
<span class="n">votes</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
</pre></div>
<p></p><br />
<p>
Let's dissect this block of code and understand the significance of each line.
</p><br >
<p>
Both the models are represented by a class that has <code>django.db.models.Model</code> as its parent class. And the fields (or columns, in SQL terms) are represented by class variables.
</p><br />
<p>
For the fields that are supposed to be persisted are represented by an instance of a subclass of the <code>Field</code> class - e.g., <code>CharField</code> for character fields, <code>DataTimeField</code> fot datetimes and <code>IntegerField</code> for integer fields and so on.
</p><br />
<p>
The name of each <code>Field</code> instance (e.g. <code>question_text</code> or <code>pub_date</code>) is the field’s name, in machine-friendly format. You’ll use this value in your Python code, and your database will use it as the column name.
</p><br />
<p>
Some <code>Field</code> classes have required arguments. <code>CharField</code>, for example, requires that you give it a <code>max_length</code>. That’s used not only in the database schema, but in validation, as we’ll soon see. They also have optional arguments; in our case we have set the <code>default</code> value of <code>votes</code> to 0.
</p><br />
<p>
Finally, note a relationship is defined, using <code>ForeignKey</code>. That tells Django each <code>Choice</code> is related to a single <code>Question</code>. Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one.
</p><br />
<h3>Migrating the Models</h3>
<p>
Django apps are basically "pluggable" modules. So here we have given Django a lot of information with our models.py code. And based on this information Django <strong>Creates the database schema</strong> and a <strong>Python wrapper API</strong> around this database for accessing the data from the database.
</p><br />
<p>
But for all this to happen we need to tell our Django project that we want the <code>polls</code> app to be installed. And to do that we add a reference to its configuration class in the <code>'INSTALLED_APPS'</code> setting we saw earlier. The <code>PollsConfig</code> class is in the <em>polls/apps.py</em> file, so its dotted path is <code>'polls.apps.PollsConfig'</code>. Edit the <em>mysite/settings.py</em> file and add that dotted path to the <code>INSTALLED_APPS</code> setting. It’ll look like this:
</p><br />
<p></p>
<div class="codehilite"><pre># Python Code
# myprojectname/settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
</pre></div>
<p></p><br />
<p>
This tells Django to include the <code>polls</code> app. Now let's make the migration files:
</p><br />
<p>
<pre>
<code>
python manage.py makemigrations polls
</code>
</pre>
</p><br />
<p>
You should see something similar to the following:
</p><br />
<p></p>
<div class="codehilite"><pre>Migrations for 'polls':
polls/migrations/0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
</pre></div>
<p></p><br />
<p>
What this does is notify Django that certain changes have been made in the models. These changes are stored in a <em>migration</em> file. This migration file is used to change the database schema. These migrations are just regular files with instructions to change the schema. We could read the migration if needed. It will be a file similar to <em>polls/migrations/0001_initial.py</em>. Reading them is not a compulsion, rather it is just to quench your thirst of curiosity.
</p><br />
<p>
These migration files do not include actual SQL statements rather it includes a intermediate python code which is used to generate the SQL commands. To view the actual SQL statements we could run the following command:
</p><br />
<p>
<pre>
<code>
python manage.py sqlmigrate polls 0001
</code>
</pre>
</p><br />
<p>
Note that the <code>0001</code> denotes the prefix of <strong>0001_initial.py</strong>
</p><br />
<p>
Let's actually write the changes to database now. This can be done by running the following command:
</p><br />
<p>
<pre>
<code>
python manage.py migrate
</code>
</pre>
</p><br />
<p>
This actually applies the changes into the database by running the migration. Django has a note of all applied migrations and runs them against the database only if not yet applied. Thus essentially syncing the changes to your database based on you your changes in Models.
</p><br />
<p>
The reason that there are separate commands to make and apply migrations is because you’ll commit migrations to your version control system and ship them with your app; they not only make your development easier, they’re also usable by other developers and in production.
</p><br />
<p>
So, the steps to remember for changing the database schema is as follows:<br />
• Change your models in <em>models.py</em> file.<br />
• Run <code>python manage.py makemigrations</code> to create migrations for the changes made.<br />
• Run <code>python manage.py migrate</code> to apply those changes to the database.
</p><br /></p>A complete guide/tutorial to Django2017-07-31T04:00:00+00:00srinath/blog/author/srinath/http://django.cowhite.com/blog/a-complete-guide-tutorial-to-django/<h3>What is Django?</h3>
<p>Django is a Python framework that make developing database driven website that can be set up in mere hours for most simple websites. The elegance of Django is that the actual coding we have to do is very less and many a boilerplate coding that every developer codes in every app is already implemented. However everything is still kept customizable and tweak-able. There is also the obvious advantage of being able to use the enormous list of Python library modules.</p>
<p><br />
<p>Django takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. And most importantly it's completely free and open source, which means Django has a huge following with thriving and active community.</p><br /><br />
<h3>Why choose Django?</h3>
<p>As we discussed earlier, we don't have to reinvent the wheel over and over again, nor do we have to copy paste a lot of boilerplate code that many common application development cycle needs. It already has built in modules ready to be used with just some few lines of code (in some case, as low as 1 line) and you are good to go! </p><br />
<p>Django helps you write software that is:</p><br />
<p><strong>Flexible</strong>:<br />Django can be used to build almost any type of website. Be it a Content Management System or an E commerce website, or be it just a blog, or a complex Vehicle tracking web app, Django can handle it all. Also Django can deliver this content in multiple formats, viz, HTML, JSON, XML, RSS Feeds to name some.</p><br />
<p><strong>Independent</strong>:<br />Although you could use the any python library from the plethora of python packages online, Django in itself is complete. In other words, Django includes everything it needs in one "product". It all works seamlessly together, follows consistent design principles, and has extensive and up-to-date documentation.</p><br />
<p><strong>Secure</strong>:<br />Django helps developers avoid many common security mistakes by providing a framework that has been engineered to "do the right things" to protect the website automatically. For example, Django provides a secure way to manage user accounts and passwords, avoiding common mistakes like putting session information in cookies where it is vulnerable (instead cookies just contain a key, and the actual data is stored in the database) or directly storing passwords rather than a password hash.
</p><br />
<p>
Django enables protection against many vulnerabilities by default, including SQL injection, cross-site scripting, cross-site request forgery and click-jacking (see Website security for more details of such attacks).</p><br />
<p><strong>Scalable</strong>:<br />Django due to its lack of dependencies on other packages and "shared nothing" architecture (each part of the architecture is independent of the others, and can hence be replaced or changed if needed), can be scaled for increased traffic by just adding hardware at any level: caching servers, database servers, or application servers. This is so due to its clear separation between each part or modules.</p><br />
<p><strong>Coder Friendly</strong>:<br />Django endorses the Don't Repeat Yourself (DRY) philosophy. Django itself is written that exhibit this principle. It's design principles and patterns encourage the creation of maintainable and reusable code. Thus reducing the overall load on coder and making the maintenance cycle as easy as ABC.</p><br />
<p>Django is written in Python, which runs on many platforms. That means that you are not tied to any particular server platform, and can run your applications on many flavors of Linux, Windows, and Mac OS X. Furthermore, Django is well-supported by many web hosting providers, who often provide specific infrastructure and documentation for hosting Django sites.</p><br />
<p><strong>Free & open source</strong>:<br />Django is completely free to use. It's open source too, due to which it has a huge community and active fan following. It also means that you'll never run out of pre-built library which you could append to your app and avoid having to code for every petty little thing and use what's already implemented and get on with stuff that matters.</p><br /><br />
<h3>What next?</h3>
<p>In the blogs to come, we will set up and learn Django in-depth; the only prerequisite being that you be familiar with Python syntax. We will understand the structure, coding style and best practices on the way and crush Django to our whim!</p><br />
<p>As and when any topic is added it will be added to the Index below, from which you could navigate through the whole series of tutorials.</p><br /><br />
<h2>Index</h2>
<ul>
<li>
1. <a href="https://django.cowhite.com/blog/installing-and-setting-up-django/">Installing and setting up Django</a>
</li>
<li>
2. <a href="https://django.cowhite.com/blog/writing-our-first-app-and-understanding-the-file-structure-of-django/">Writing our first app and understanding the file structure of Django</a>
</li>
<li>
3. <a href="https://django.cowhite.com/blog/models-migrations-and-django-admin/">Models and Migrations</a>
</li>
</ul></p>