Django入门文章1

本系列教程适用于Django入门,文章翻译自官方英文文档,在官方文档的基础上进行web开发和python语言学习的扩展。下面就开始了。请指教。

设计model

web开发的基础是数据。Django中可以不直接对数据库进行操作,使用ORM对数据进行描述。下面是一个入门例子:

    from django.db import models
    
    class Reporter(models.Model):
        full_name = models.CharField(max_length=70)
    
        def __str__(self):
            return self.full_name
    
    
    class Article(models.Model):
        pub_date = models.DateField()
        headline = models.CharField(max_length=200)
        content = models.TextField()
        reporter = models.ForeignKey(Reporter)
    
        def __str__(self):
            return self.headline

本例中定义了两个集成自models.Model的类 Reporter和Article。

安装

    python manage.py migrate
    
    D:\proj\mysite>python manage.py migrate
    Operations to perform:
      Apply all migrations: admin, contenttypes, polls, auth, sessions
    Running migrations:
      Applying contenttypes.0001_initial... OK
      Applying auth.0001_initial... OK
      Applying admin.0001_initial... OK
      Applying polls.0001_initial... OK
      Applying sessions.0001_initial... OK

migrate命令检查所有的models,创建在数据库中没有建立。

1. python manage.py makemigrations
2. python manage.py migrate

创建新的model的时候,分别执行上面的步骤。把数据库更新。

自由的api

    D:\proj\mysite>python manage.py shell
    Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
    32
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> from news.models import Reporter,Article
    >>> Reporter.objects.all()
    []
    >>> r = Reporter(full_name="John Smith")
    >>> r.save()
    >>> Reporter.objects.all()
    []
    >>> r.id
    1L
    >>> r.full_name
    'John Smith'
    >>> Reporter.objects.get(id=1)
    
    >>> Reporter.objects.get(full_name__startswith='John')
    
    >>> Reporter.objects.get(id=2)
    Traceback (most recent call last):
      File "", line 1, in 
      File "C:\Python27\lib\site-packages\django-1.7.1-py2.7.egg\django\db\models\ma
    nager.py", line 92, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "C:\Python27\lib\site-packages\django-1.7.1-py2.7.egg\django\db\models\qu
    ery.py", line 357, in get
    self.model._meta.object_name)
    DoesNotExist: Reporter matching query does not exist.
    >>> from datetime import date
    >>> a = Article(pub_date=date.today(), headline="Django is cool", content="Yeah"
    , reporter=r)
    >>> a.save()

api的学习需要看相关文档,了解Django的ORM如何对数据库进行操作。

看数据库的时候发现了一个外键的问题:

  1. 外键关联的是一个对象,自动生成的外键名称会在关联的对象的名称后面加上个"_id"作为字段名称
  2. 默认情况下,外键会自动创建索引,会自动做级联删除,默认的外键是

Admin接口

不仅是一个基架,更是一个整体。Django能创建一个专业的管理Model对象的接口。
编辑mysite/news/admin.py文件

    from django.contrib import admin
    from . import models
    admin.site.register(models.Article)

设计URLS

创建一个叫URLconf的python module。设计一个urls.py

    from django.conf.urls import patterns
    from .  import views
    
    urlpatterns = patterns('',
        (r'^articles/(\d{4})/$', views.year_archive),
        (r'^articles/(\d{4})/(\d{2})/$', views.month_archive),
        (r'^articles/(\d{4})/(\d{2})/(\d+)/$', views.archive_detail),
    )

设计Views

每个view负责返回一个HttpResponse object或者返回一个404异常。

一个简单的例子。

    from django.shortcuts import render
    
    from .models import Article
    
    def year_archive(request, year):
        a_list = Article.objects.all()
        context = {'year':year, 'article_list':a_list}
        return render(request, 'news/year_archive.html', context)

获取数据,把数据渲染到模板上。

你可能感兴趣的:(Django入门文章1)