Django学习笔记(四)Django使用操作数据库

1.增加(修改)操作:

urls中增加insert入口:

url(r'^blog/db/insert', 'blog.views.insert'),

views中增加insert方法:

def insert(req):
    #way_1
    user1 = Users()
    user1.name = 'sid'
    user1.sex = 'f'
    user1.save()
    # way_2
    user = Users(name='tom',sex='f')
    user.save()
    # way_3
    user2 = Users.objects.create(name='lilei',sex='f')
    print 'insert:'+user2.name
    
    #update
    Users.objects.filter(name='sid').update(sex='m')
    return render_to_response('db.html',{'user':user})

2.删除操作:

urls中增加删除入口:

url(r'^blog/db/delete', 'blog.views.delete'),
views中增加删除模块:

def delete(req):
    #way_1
    Users.objects.filter(name='lilei').delete()
    return render_to_response('db.html',{'user':''})

3.查询操作:

urls中增加查询入口:

url(r'^blog/db/select', 'blog.views.select'),
views中增加查询模块:

def select(req):
    users = Users.objects.all()
    for user in users:
        print 'all:'+user.name
    users = Users.objects.filter(name='sid')
    for user in users:
        print 'filter:'+str(user.id)+'_'+user.name
    users = Users.objects.get(id=16)
    print 'get:'+users.name
    return render_to_response('db.html',{'users':users})

4.多对一关系:

class Users(models.Model):
    sex_choices=(
        ("f","famale"),
        ("m","male"),
    )
    name = models.CharField(max_length=30)
    sex = models.CharField(max_length=1,choices=sex_choices)

    def __unicode__(self):
        return self.name
    
    
class Blog(models.Model):
    name = models.CharField(max_length=30)
    #many to one
    user = models.ForeignKey(Users)

    def __unicode__(self):
        return self.name
python中多对一关系,定义好model之后,同步数据库:python manage.py syncdb;会在多的一端生成对应一的外键

查询时:

blog.user

blog.user_id

user.blog_set.all()


5.多对多关系:

class Author(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=30)
    # many to many
    authors = models.ManyToManyField(Author)

    def __unicode__(self):
        return self.name

python中多对多关系,定义好model之后,同步数据库:python manage.py syncdb;会生成一张中间表用于存放两者的id

查询时:

book.authors_set.all()

author.book_set.all()

增加:

author.book_set.add(book)
author.book_set.create(book(name='python'))


个人觉得目前这些操作足够完成一般的数据关系了。一对一关系可以看成是另一种多对一的关系

你可能感兴趣的:(Python框架)