At the Forge - Database Modeling with Django
Listing 2. views.py, with an Index Method
from django.template import Context, loader from django.http import HttpResponse from blog.models import Posting from datetime import * def index(request): postings = Posting.objects.all().order_by("-publication_date") output = "" for posting in postings: output += "<h1>%s</h1>\n" % posting.title output += "<h2>%s</h2>\n" % posting.publication_date.isoformat() output += "<p>%s</p>\n\n\n" % posting.body return HttpResponse(output)
You can try all of these database queries for yourself using Django's shell:
python manage.py shell
Using the Django shell, as opposed to the straight interactive Python interface, ensures that Django-related classes and paths are preloaded, making it possible to query and modify the database from within Python interactively. This is a good way to experiment with new code that you are thinking of adding to a view method, without having to place it in a file.
Django provides a high-level interface for the definition of database models using Python, rather than SQL. This high-level API permeates the framework, making it possible to work exclusively in Python. Moreover, the API includes many convenience functions and data types that make it relatively natural to work in this way. Creating database-backed Web applications with Django is dramatically easier and better than with most frameworks I've used, although it is similar in style to Ruby on Rails. Whether you should use Django or Rails is a matter of personal taste and also depends on what others in your organization are using, but there's no doubt that if you're a Python Web/database hacker, Django is worth a very serious look.
Reuven M. Lerner, a longtime Web/database consultant, is a PhD candidate in Learning Sciences at Northwestern University in Evanston, Illinois. He currently lives with his wife and three children in Skokie, Illinois. You can read his Weblog at altneuland.lerner.co.il.
|Privacy Is Personal||Jul 02, 2015|
|July 2015 Issue of Linux Journal: Mobile||Jul 01, 2015|
|July 2015 Video Preview||Jul 01, 2015|
|PHP for Non-Developers||Jun 30, 2015|
|A Code Boot Camp for Underprivileged Kids||Jun 30, 2015|
|Comprehensive Identity Management and Audit for Red Hat Enterprise Linux||Jun 29, 2015|
- Privacy Is Personal
- PHP for Non-Developers
- Secure Server Deployments in Hostile Territory
- Linux Kernel 4.1 Released
- Django Templates
- July 2015 Issue of Linux Journal: Mobile
- Comprehensive Identity Management and Audit for Red Hat Enterprise Linux
- A Code Boot Camp for Underprivileged Kids
- Attack of the Drones
- Practical Books for the Most Technical People on the Planet