magpiebrain

Sam Newman's site, a Consultant at ThoughtWorks

Since lambasting someone for a less than fair Django and Rails comparison, I’d planned to do my own. To start with, my comparison is based on several days worth of Rails development and about a weekend’s worth of playing with Django, using the (currently four part) tutorial.

I’ve had this reviewed by both Rails and Django developers, but if you think I’ve misrepresented anything or left anything out then feel free to leave a comment and I’ll make sure to put it right.

Background

Rails is framework which emerged from the development of a web application, Basecamp. Django was emerged from the development of the highly successful Lawrence Journal World. Both applications were written in situations and organisations that historically would have ended up being written in Perl or PHP – but ended up being written in Ruby and Python respectively.

The fact that both frameworks were the result of development of specific applications means that both frameworks are focused on supporting those specific types of application. As a framework Rails has been around for little over a year, whereas as a framework in its own right django has only been public for around two months. Neither has yet made it to version 1.0.

Languages

On the face of it, the biggest difference between the two has been the choice of development language. Outside of Japan Ruby has made little impact despite having been around as long as Python – a colleague of mine once said that the number of Python programmers in London probably outnumbered the number of Ruby programmers in Europe and the US and he’s probably not wrong. Anyone having to consider which of the two frameworks is right for them is inevitably going to have to think about the task of hiring people and this may have an impact on their choice.

Ruby does seem to have some more powerful language features – it has slightly better closure support than Python (although perhaps not enough to be a differentiating factor) and the extremely useful mixins. Ruby’s OO support also feels much cleaner. Both support inheritance (Python supports multiple inheritance, which Ruby’s mixins more than make up for). But the requirement that self be passed in to all python instance methods drives me potty.

On the other hand Python has a much cleaner syntax (which given its background is no surprise) – more than once I’ve found myself using a third type of parenthesis in the same Ruby method quite validly, only for me to look back at what I’ve done and feel that I’d regressed to the bad old days of Perl. It would be nice to think that one day a language will come along which manages to add powerful features without making the code look like it’s been rendered with the wrong character encoding.

Ultimately comparing two languages that are so close (they’re certainly more similar to each other than Java or .NET) is going to come down to personal choice or a specific requirement. But for more indepth comparisons you’ll no doubt find many out there on the web.

Requirements and installation

Installing both Rails and Django is fairly easy once you’ve got the relevant interpreter installed. Ruby can make use of the excellent Gems system, which is something Python (and to be fair most other languages including Java) would do well to mimic.

Both also come with their own webserver for development purposes, which is great from a developer’s point of view. There should be anything stopping you from getting both up and running fairly quickly

Deployment options

Both Python and Ruby suffer from a similar global interpreter lock problem – basically neither the Ruby nor Python interpreters are completely thread safe. When running multi-threaded applications a lock has to be acquired by a thread before it can access any objects. That means that both Ruby and Python scale by using multiple instances of the interpreters rather than the Java approach of using multiple threads – as a result the deployment options are fairly similar.

Django’s current recommended deployment is using Apache and mod_python, although there is no reason why fastcgi couldn’t be used, or even an alternate server such as lighttpd (which is TextDrive’s current approach to hosting Rails).

One important point is that Django currently only supports Sqlite, MySql and Postgres (although support for Oracle has already been submitted to the project), whereas Rails supports virtually all the major relational databases.

Caching

Django’s heritage as a framework supporting large, high-volume websites shows through clearly in the built-in support for a variety of caching options. Rails’ own caching doesn’t seem as flexible. With Django multiple caching backends are supported (in memory, memcached, or DB) coupled with supporting caching at multiple levels – either for a whole site, a specific page or fragment (like Rails), or even a specific object.

Setting up a project

Both frameworks generate your project structure for you. Django actually has separate concepts of Project and Application (of which more later). Rails goes a little further – it also generates a build file and stub tests (I won’t call them Unit tests as Rails does, because they’re not). There is nothing to stop you testing Django of course – it’s just as testable as Rails – however it would be nice to get some guidance on how to do it. My feeling is many people new to testing are more likely to do it with Rails because it’s built right in and it’s well documented.

Adding models

In Rails, you define a table that represents your model, and then generate the stub code to create a Rails model that binds to the table. You are then free to build upon the stubs. With Django, you define your model in Python code, and have Django generate (and even execute) the schema for your model.

The fact that your Python code can be the canonical reference for your models means understanding can be simplified. It can seem odd to be adding code to a Rails model and not know exactly what attributes your model has without referring to the database schema. The fact that Django can generate the SQL from you model also leads to flexibility in development – for example a developer can use Sqlite which is fast use and trivial to setup, but deploying onto MySql or Postgres is easy as you can regenerate the SQL for your target database from the Python code – that the SQL for both databases might need to be different is hidden from you.

Early on your model will be constantly changing – I’ll often find myself writing some Rails code, need to add a new attribute to a model, have to change my (DB-specific) schema. With Django I change my model and regenerate the SQL. The only minor annoyance is that there is no equivalent of a model-specific SQL refresh – something that could drop a specific model’s tables and regenerate the needed SQL automatically. Instead you have to have the admin script dump out the SQL to the command prompt and run it in yourself.

Django’s generation of schema also extends to creating lookup tables for many-to-many relationships.

The downside to having Django generate the SQL schema is that there is more work involved in supporting databases – currently only MySQL, Postgres and Sqlite are supported, although I’d be highly surprised if support for other databases wasn’t on the way.

Django does seem to offer the ability to reverse-engineer models from an existing schema, although I don’t have information as to how sophisticated this is (for example to what extent it can determine inter-model relationships).

Another thing to note is that unlike Rails Django doesn’t allow you to manage your own transactions (although it is going to be added). I’ve not found myself needing it in my Rails or Django work to date, although as a J2EE programmer not having the ability to control this if I need to is a minor concern for me.

Interaction with the Database

Both Django and Rails have taken the decision to bind models to the database. Methods to save, delete or lookup objects are called on the models themselves. Neither specifically stops you from providing proper separation, but if you do you’re on your own. Going forward it will be interesting to see if either Rails or Django start providing the ability to have a clean repository layer as nicely as they do the current DB access, although it will probably require both of these frameworks to be used in more complex situations than they are currently.

One nice thing Django offers is the ability to write your own SQL in the model to access attributes. Rails does nothing to stop you calling SQL directly, but the fact that with Django you are doing this custom lookup in the same place as the definition of the other attributes (whereas with Rails it would be split between the schema and Rails model) results in something much cleaner.

Projects and Applications

A nice touch with Django, and another example of the environment in which it was developed, is that there is a project in which you can have pluggable applications. This should hopefully lead to smaller (Rails-style) apps being created, reused and integrated easily into a larger Django projects. This was something that was demonstrated wit LJWorld, with new parts being added incrementally without a need to deploy the whole site.

Controllers and URLs

With both Rails and Django URLs are mapped directly to code. Rails automatically generates stub controllers to map to the scaffolding (of which more later), whereas with Django you have to create them yourself.

With Django you use regular expressions to define URL’s that bind to your python code. That makes it much easier to create RESTful URLs – in fact all of the tutorials reinforce this. The fact that you have RESTful URLs happens to make controlling code simpler is just an added bonus.

By default Rails gives you URL’s in the form controller/method – but these can be edited using the routes.rb file to give you proper RESTful (or not) URL’s. Unlike Django’s pseudo mod_rewrite approach, Rails uses Ruby code to handle routing, which depending on your point of view could be considered more readable.

The URL to code mapping can be specified either for a whole project or (more likely) for a single application.

Templating options

Both Django and Rails template using embedded Python or Rails code (like using Java scriptlets in JSP pages). Much more work has been put into Rails’ helper code – Ruby code you can use to generate HTML constructs – its excellent Ajax support being one example. Django does make it fairly easy to swap in other templating options if required (such as Zope’s Template Attribute Language, or perhaps Clearsilver). I’m less savvy on alternate templating options available for Rails – although obviously if you used something else you’d have to do without many of the helper methods available.

Administration and User management

Django’s administration interface is simply excellent. Unlike Rails’ scaffolding views, it is not designed to be viewed by everyone (being an Admin console), but unlike the scaffolding it is perfectly functional and you could imagine making use of it without alteration in a production application.

The administration console is password protected – you can generate a superuser account using the command line admin script. Once you’ve logged in you can add more users and even groups – Django automatically generates permissions for both the admin functions and your models which can be assigned to a group.

You can also add new model instances in the same way as Rails scafolding, but the view is much better. You have nice popups and shortcuts for date and time fields, dropdown lists for one-to-many relationships, and multi-select lists for many-to-many relationships all provided without any developer interaction.

Rails does have a measure of user administration in the form of the add-on salted login hash generator, but despite some hard work by the developers it does seem problematic and nowhere near as slick as Django.

So which is right for you?

I said at the start that the two frameworks were developed as a result of two very different applications – and most of the differences between the two are a result of this. If you are developing a simple (in a domain model sense) application where you want to use Ajax to deliver a great UI, Rails is probably for you. If however you want to develop an entire site with different types of applications within it – then Django’s plugable applications and general approach might be what you’re after. Equally, the better user and administration side of Django favours portal style applications – this is something you’ll have to do yourself if you want to use Rails.

There is scope for both frameworks to learn from each other, and I still have a question around how well Rails will scale (in terms of the size of the site, not number of hits) – Django has already proved it is capable of this with LjWorld.com. Likewise it will be interesting to see if Django can or even wants to make the use of Ajax as simple as it is with Rails (although work is already progressing along these lines), or if the more powerful language features of Ruby will prove the deciding factor.

Personally, given my own current projects I’ll be spending some more time with Django – but all that means is that it is one more tool that will sit alongside Ruby, Rails and J2EE in my particular toolbox. And just like Java web frameworks before, I fully expect to see more and more web frameworks based on dynamic languages (such as Nitro or SeaSide) start to gain more visibility and yet more options. It seems we’re going to be spoilt for choice.

About these ads

61 Responses to “A comparison of Django with Rails”

  1. Counsel

    “I never understood why companies hire technologies instead of people.”

    Actually, I think the quote should be firms choose technologies, then hire the people to implement those technologies.

    If you are making a web-site that will allow customization, you are likely looking at “AJAX” just like the firm that wants to generate ‘buz’ for their project. The use of a particular technology, right or wrong, attracts attention–marketing.

    I don’t know why everyone is so ‘offended’ by comaprisons that, in my opinion, are subjective. Even an ‘objective’ comparison showing features would be subjective in that someone had to select which features were put in the table (unless they all were?).

    Python, Ruby, Rails, Django, Javascript, PHP, etc. are all tools. Not all are required to be a ‘web developer,’ but some may make your job easier, more efficient, etc.

    These tools are like patterns on silverware-they make the spoon ‘look’ (to the coder/developer) different, but the web site, if you have done your job, will work regardless of the tool you have chosen.

    Reply
  2. Tan

    I’d like to see you include Catalyst as well. From what I’ve read, it’s very flexible and can provides the same thing that Rails and Django have. But remember to grab a copy of Perl Best Practices before digging any code :)

    Reply
  3. jake

    If we’re to use Python/Django, what are our options as far as forum software and blog software goes? The reason I use PHP is that I can use stuff like WordPress and PunBB. For Rails, Typo and whatever, Rforum, just aren’t there yet. And I haven’t even heard of what’s available for Python/Django.

    Reply
  4. sam

    I’m a great believer in ‘right tool for the job’. If you need to build a solution that integrates blogging and forum software, PHP still has the best options out there (e.g. WordPress + bbpress, drupal etc). If you aren’t going to add much to these products in terms of customisation, then you’ll probably be better off. If you’ll need to write a lot of your own code in addition to the basic forum/blog software, the inherent improvements in efficiency of Django or Rails might make sense.

    Reply
  5. Namgo

    I don’t know about how rails handle the new-full-featured widgets for the web but django does not handle this in a nice way. It’s still repetitive and just painfull… You may say that it’s not its purpose ? But what do you mean by web application so ?

    Reply
  6. greenkid

    Hi,

    Like Daniel Schmidt above, I’m wondering which, RoR or Django, would be a better choice for someone with less experience. I’ve inherited a very large but mostly static site built in PHP, and am working on a redesign. We will be integrating some kind of content management (we’re non-profit, so maybe some open source, do-it-ourselves, or cheap option). Right now, it uses Dreamweaver templates and Contribute, which to me is not very scalable (the need to update and upload all pages whenever a template change is made). We also have ideas for more database driven projects on the horizon.

    I had assumed I’d build the site with PHP and SQL, but now am wondering, because our organization is always changing direction, whether I ought to go with something that lends itself to more rapid development.

    So that’s how I ended up looking into frameworks. My background is that I’ve done lots of XHTML, CSS, Javascript and a little PHP. I also built large-scale web applications that had an old mainframe database (ADABAS), the procedural language Natural, and a proprietary scripting language (a bit like ASP classic) running (weird, I know). So while I have a mixture of experience, I’m not a programmer with solid modern skills. That said, I’m a quick learner.

    Anyone have any thoughts on which would be easier to pick up and run with for, and lend itself to content management for end-users? And then be easily maintainable for future people and projects? It will just be me and one other yet-to-be-hired developer creating and maintaining the site for the forseeable future.

    Any thoughts anyone has on the beginner-friendliness of these frameworks would be very much appreciated.

    Reply
  7. portrait artist

    I’m learning about Django on my own lately. I am following the tutorials from the Dajngo book. At chapter four, I am first getting the following error after running from django.template import Template in the python shell.

    environment variable DJANGO_SETTINGS_MODULE undefined

    Next I tried to fix this by adding a Windows system variable:

    variable: DJANGO_SETTINGS_MODULE

    path: c:/temp/mysite (this is where my project lives)

    Now after running the above command I get the following errors:
    raise EnvironmentError, “Could not import settings ‘%s’ (Is it on
    sys.path? Does it have syntax errors?): %s” % (self.SETTINGS_MODULE, e)
    EnvironmentError: Could not import settings ‘c:tempmysite’ (Is it on
    sys.path? Does it have syntax errors?): No module named c:tempmysite

    What must I do next?

    Reply
  8. tom

    I of course got to this article looking to compare Django to Rails.

    One point I have been looking at extensively is the ability to internationalize applications and models without reinventing the wheel. It appears that Rails has this pretty much nailed with the Globalize2 plugin, but that Django hasn´t been able to get it´s act together in supporting multilingual model fields. At first I lean to Django, but if it is going to slow down how long it takes to add i18n to my app then I will prob go with Rails. Anybody have experience putting together a site with multilingual content and models in either framework?

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Basic HTML is allowed. Your email address will not be published.

Subscribe to this comment feed via RSS

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: