Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Why Django?

$
0
0

With the release of our firstDjango course, Try Django, this month, you may be wondering if Django is for you. Django is a python framework that allows you to get a fully functioning web app up and running quickly, and is often compared to Ruby on Rails, since they both offer similar functionality and follow the Model View Controller (MVC) pattern. Today, I’ll be talking through the similarities and differences between the two so you can be better informed when choosing a framework for your next project.

Python and Ruby

One obvious difference is that Ruby on Rails uses Ruby, whereas Django uses Python. However, using these frameworks doesn’t mean you have to know either Ruby or Python inside and out ― knowing the basics will allow you to create a simple app. There are framework-specific things you will also have to learn that are separate from Python or Ruby that have to do with database concepts and rendering HTML.

The MVC (or MTV) Pattern

I said before that both use a Model-View-Controller (MVC) pattern, which is true, but Django names its components slightly differently. Django templates render HTML dynamically, so Template replaces View in Django. And Django views actually control what data is displayed to the user, so View replaces Controller in Django. Hence, in Django, Model-View-Controller (MVC) becomes Model-Template-View (MTV). Somewhat confusing, I admit, but as soon as you see these components working together, you get the reasoning behind this naming convention switch. Also, in Rails, the term “route” is used to point a URL to a controller. However, in Django, URLs are just called URLs, and the URL Dispatcher handles pointing a URL to its matching view.

The ORM

Both have a built-in ORM (or Object Relational Mapper) that allows database queries to be written in Python or Ruby code directly instead of using SQL statements. The ORM then handles communicating with the database. This level of abstraction helps in writing code, but also makes it easier to switch between different relational databases. For example, if you’re using SQLite in development, you can switch to PostgreSQL when you deploy with minimal code modifications.

Models and Migrations

Both also have database migrations, which are extremely helpful in propagating changes you make to your models into your database schema. These migrations also act like a version control system for your database. One old complaint about Django is that it didn’t originally have migrations, but those have been included for a few years now since Django 1.7. I personally prefer Django’s way of organizing models and database migrations. In Django, when you want to change a table, you (1) change the model file ( models.py ) directly, and (2) start the migration commands makemigrations and migrate . Then, the corresponding table in the database is changed. And you can then find your model definitions and fields in one place: the models.py file.

Database Migration in Django

For example, here’s a database migration in Django:

# models.py class Soup(models.Model): name = models.CharField(max_length=80) featured = models.BooleanField(default=False) manage.py makemigrations manage.py migrate

Then if you want to add a new field called image, just edit models.py :

# models.py class Soup(models.Model): name = models.CharField(max_length=80) featured = models.BooleanField(default=False, required=False) image = models.CharField(max_length=200)

And re-run migrations:

manage.py makemigrations manage.py migrate

In Rails, on the other hand, you don’t change the model file, but generate a migration file from the command line for every change you want to make. You can view your database schema in schema.rb , but there isn’t a list of model fields that you can edit directly like in Django.

Database Migration in Rails

Originally creating the models:

rails generate model Soup name:string featured:boolean category_id: integer rake db:migrate

Want to add a new image field:

rails generate migration AddImageToSoup image:string rake db:migrate

Above is a little bit of Rails convention magic. If the migration name is of the form AddXXXToYYY and is followed by a list of column names and types, then a migration containing the appropriate add_column and remove_column statements will be created.

# models.py class Soup(models.Model): name = models.CharField(max_length=80) featured = models.BooleanField(default=False, required=False) image = models.CharField(max_length=200)

Also notice that for Django, the validators such as max_length and required and any relationships are conveniently set in models.py. But for Rails, validators and relationships need to be added to model’s .rb file. Here, soup.rb would be generated and we could add validators as follows.

# soup.rb class Soup < ActiveRecord::Base validates :name, presence: true, uniqueness: true end Convention vs. Configuration, or “Magic” Over Control

Rails emphasizes convention over configuration where many things “magically” happen for you just by following certain naming conventions. Django, on the other hand, provides more flexibility by relying on configuration. For example, in Rails, to create a route that shows a certain soup by id, you can use HTTP verbs like the following in routes.rb :

get '/soups/:id', to: 'soups#show'

Or if you followed Rails’ naming conventions when naming your controller methods, this command will automatically map the following routes in routes.rb :

# automatically maps GET /soups/:id to soups#show # GET /soups to soups#index # POST /soups to soups#create # DELETE /soups/:id to soups#destroy # etc. resources :soups

In Django, though, regular expressions match URLs and map them to controllers. Since Django doesn’t rely on convention, it doesn’t have a helper like Rails’ resource , but it does have flexibility in configuration.

# urls.py urlpatterns = patterns('', # matches the detail view url(r'^soups/(?P\d+)/$', views.detail, name='detail'), # matches the index view, etc. url(r'^soups/$', views.index, name='index'), url(r'^soups/create/$', views.index, name='create'), url(r'^soups/(?P\d+)/delete/$', views.delete, name='delete'), ) The Admin

Another great built-in feature Django offers is the admin interface that allows you to view and change your database tables. To get this functionality in Rails, you need to install an external library of your choice.


Why Django?
Project and App Structure

Last, but not least, I really like Django’s project structure. In Django, you have an outer project with separate apps inside. Each app is responsible for a specific behavior ― for example, you could have separate apps for the main .com, the blog, and the store. Apps then have their own models, templates, and views, but they can be connected to each as well. They can also share settings by using the outer project. This format gives you a cleaner structure when you have a big project.

Conclusion

All in all, both frameworks streamline the process of making modern web apps, and people are fans of each for different reasons. I personally love Python, so it’s an easy choice for me. Now that you’ve seen the similarities and differences, you can make the choice for yourself ― and you can see that if you put in a little bit of time, it’s not too difficult to make the jump from one framework to another. Get a feel for Django now by playing through our newDjango course, Try Django, and see if it’s a good fit for your own projects!


Viewing all articles
Browse latest Browse all 9596

Trending Articles