Django(四)模型开发与数据库交互

修改时间: 2016-12-07

修改次数: 1


创建Models

Django1.8+django移除了syncdb命令

#models.py

from django.db import models
# Create your models here.
class BlogPost(models.Model):
    title = models.CharField(max_length=150)
    url = models.URLField()
    author = models.CharField(max_length=100)
    num = models.CharField(max_length=10)
    
    #这句是配合后台管理时,方便阅览。可以不加下面这2行再去试试管理这个类就明白了。
    def __unicode__(self):
        return self.title
        
        
class Content (models.Model):
      title=models.CharField(max_length=140)
      Con = models.ForeignKey(BlogPost) #外键设置
      
      def __unicode__(self):
          return self.title
      

设置setting.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'USER':'root',
        'PASSWORD':'111111',
        'NAME':'Djangotest',
        'HOST':'localhost'
    }
}

我使用的是pyMysql,如果你有mysqldb的话,无须下一步的操作。

设置init.py

import pymysql
pymysql.install_as_MySQLdb()

运行:

python manage.py migrate #移植操作
python manage.py makemigrations #Model迁移进数据库

查询


from blog.models import *
B=BlogPost.objects.all()
print B #打印对象实例
print B[0].title #打印具体内容

模糊查询

B[0].title.filter(name__contains='p')#模糊查询where name like '%p%'

多对多及外键

class Publisher(models.Model):

        name = models.CharField(max_length=30)
        address= models.CharField(max_length=30)
        city = models.CharField(max_length=30)
        countiy = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name

class Author(models.Model):
        names= models.CharField(max_length=30)
        qq= models.CharField(max_length=15)

    def __unicode__(self):
        return self.names


class Book(models.Model):
        title=models.CharField(max_length=30)
        authors=models.ManyToManyField(Author)#多对多
        publisher = models.ForeignKey(Publisher)#外键

    def __unicode__(self):
        return self.title


#使用
p=Publisher.objects.get(id=1)
p.book_set.all() # 外键值

a=Author.objects.get(id=1)
a.book_set.all() #多对多

自定义Manager实例

#views.py

def hello(request):
    b=Book.get_book_count('Django')
    return render_to_response('1.html',{'book':b,'count':count})


#models.py

class BookMananger(models.Manager):
    def get_book_count(self,keyword):
        return self.filter(title__icontains=keyword).count()

class Book(models.Model):
        title=models.CharField(max_length=30)
        authors=models.ManyToManyField(Author)#多对多
        publisher = models.ForeignKey(Publisher)#外键
        object=BookManager()

    def __unicode__(self):
        return self.title


#使用
m=Book.object.get_book_count('django')

自定义QuerySet实例

#models.py
class PythonManager(models.Manager):
        def get_query_set(self): #重写get_query_set
                return super(PythonManager,self).get_query_set().filter(title__icontains='django')

class Book(models.Model):
        title=models.CharField(max_length=30)
        authors=models.ManyToManyField(Author)#多对多
        publisher = models.ForeignKey(Publisher)#外键
        object=BookManager()
        python_objects=PythonManager() #使用

     
    def __unicode__(self):
        return self.title

#使用
m=Book.python_objects.all()

查询-限制

B=BlogPost.objects.all()[0:5] #前五条数据

插入数据

m=BlogPost(title='yy',url='21')
m.save()

数据过滤

m=BlogPost.objects.get(url='21')
print m

排序

m=BlogPost.objects.all().order_by('num')#升序
m=BlogPost.objects.all.order_by('-num')#降序

class BlogPost(models.Model):
    title = models.CharField(max_length=150)
    url = models.URLField()
    author = models.CharField(max_length=100)
    num = models.CharField(max_length=10)

    class Meta:
        ordering=['num'] #或者像这样,默认的排序方式,上面的操作就可以不做了

m=BlogPost.objects.get(num=2)
m.title='Python'
m.save()

m=BlogPost.objects.get(num=2)
m.delete()

你可能感兴趣的:(Django(四)模型开发与数据库交互)