Django 记录

1. ManyToManyField字段的修改

ManyToManyField字段须要在记录被创建后再进行更新,如下边的例子:

from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()
    def __unicode__(self):
        return self.name

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()
    def __unicode(self):
        return title
#-*-coding:utf-8-*-

from books.models import *

def init_db():
    dianzigongye = Publisher(name=u'电子工业出版社',
                                        address=u'海淀区万寿路',
                                        city=u'北京',
                                        state_province=u'北京',
                                        country=u'中国',
                                        website=u'http:/www.phei.com.cn')
    dianzigongye.save()
    renminyoudian = Publisher(name=u'人民邮电出版社',
                                        address=u'崇文区夕照寺路',
                                        city=u'北京',
                                        state_province=u'北京',
                                        country=u'中国',
                                        website=u'http:/www.ptpress.com.cn')
    renminyoudian.save()

    boothby = Author.objects.create(first_name=u'William M',
                                        last_name=u'Boothby',email='')
    deitel = Author.objects.create(first_name=u'H M',
                                        last_name=u'Deitel',email='')
    liuwenhong = Author.objects.create(first_name=u'',
                                        last_name=u'文红',email='')
    bentley = Author.objects.create(first_name=u'Jon',
                                        last_name=u'Bentley',email='')
    huangqian = Author.objects.create(first_name=u'',
                                        last_name=u'',email='')
    zouxin = Author.objects.create(first_name=u'',
                                        last_name=u'',email='')

    bianchengzhimei = Book(publisher=dianzigongye,
                                        publication_date = '2008-03-01')
    bianchengzhimei.save()
    bianchengzhimei.title = u'编程之美'
    bianchengzhimei.authors = Author.objects.filter(first_name='',
                                        last_name='')
    bianchengzhimei.save()

    bianchengzhuji = Book(publisher=renminyoudian,
                                        publication_date = '2008-01-01')
    bianchengzhuji.save()
    bianchengzhuji.title = u'编程珠玑'
    bianchengzhuji.authors = Author.objects.filter(first_name=u'Jon',
                                        last_name=u'Bentley')
    bianchengzhuji.authors.add(huangqian)
    bianchengzhuji.save()

    csharp = Book(title=u'Visual C# 2005 大学教程(第二版)',
                                        publisher=dianzigongye,
                                        publication_date = '2007-07-01')
    csharp.save()
    csharp = Book.objects.filter(
                                     title=u'Visual C# 2005 大学教程(第二版)')
    csharp[0].authors = Author.objects.filter(first_name=u'H M',
                                        last_name=u'Deitel')
    csharp[0].authors.add(liuwenhong)
    csharp[0].save()

    manifold = Book(publisher=renminyoudian,
                                        publication_date = '2007-10-01')
    manifold.save()
    manifold.title = u'微分流形与黎曼几何引论'
    manifold.authors = [boothby]
    manifold.save()

 原因参考MWI的日志

生成了四个表。
其中book_authors表是关联表,不能直接插入数据,实际上也不存在叫做BookAuthors的对象。所以要插入这里面数据,建立起book和author的联系时,必须取出book实例,并给book赋值

2. 要使django数据库相关的设置修改生效的最简单方法是退出由语句“python manage.py shell”启动的命令行终端,然后再次启动它

3. django中通过models建表时,翻译过来的字段SQL语句默认都是NOT NULL的,如果编程时留空一个字段,那么django在数据库中建表时会用""空字符串去填充该字段,防止它真的为空,即成为NULL。但是日期型、时间型和数字型字段不接受空字符串,因此不能留空,必须赋个值。如果要改变默认,将其定义为可以为空的字段,则需要表模型中通过null=True定义:

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField(null=True)
bianchengzhuji = Book(publisher=renminyoudian,publication_date = '2008-01-01')
bianchengzhuji.save()

4. 在编辑模板文件时,最好不要使用记事本,因为记事本程序在将文本另存为utf-8格式时,在文件头额外添加了三个字节的数据BOM,用以给记事本等程序提示应按utf-8编码格式读取该文件。但着三个多余的字符,在django中处理utf-8文件时,会造成显示窜出一行。推荐使用UltraEdit或Dreamweaver等,在保存为utf-8格式时将有关BOM的选项取消。

5. 字符编码最好全部使用utf-8,包括但不限于:程序源文件的编码设置(通过注释#-*-codingutf-8-*-设置);程序中字符常量(通过u'xxx');数据库的数据存储编码,在mysql中,通过以下语句设置(fromjxst051665的博客

Create DATABASE IF NOT EXISTS my_db default charset utf8 COLLATE utf8_general_ci;

6. 视图函数中不要有url硬编码,也不要使用url字符串相关变量进行判断,如果url字符串相关变量被传递进视图函数,在函数内不要拿它做其他事,最后return rend_to_response出来就行了。有关url的事情,尽量都在url配置中完成。如下面的例子:

BAD CODE

1 urlpatterns = patterns('',
2     # ...
3     ('^([^/]+)/([^/]+)/add/$', views.add_stage),
4     # ...
5 )
# app_label,model_name是patterns中正则表达式提取得到url中的两个变量,下面视图函数中使用其进行了逻辑判断
def
add_stage(request, app_label, model_name): if app_label == 'auth' and model_name == 'user': # do special-case code else: # do normal code

GOOD CODE

urlpatterns = patterns('',
    # ...
    ('^auth/user/add/$', views.user_add_stage),
    ('^([^/]+)/([^/]+)/add/$', views.add_stage),
    # ...
)
def add_stage(request, app_label, model_name):
    # ...
def user_add_stage(request):
    # ...
 

 

posted on 2013-04-13 19:22  ByThisRiver  阅读(519)  评论(0编辑  收藏  举报