QuerySet 测试项目
安装包
#下载后从终端进入文件目录,进行如下操作:
python setup.py install
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
DATABASES = {
'default': {
'ENGINE' :'django.db.backends.mysql',
'NAME' :'sys',
'USER' :'root',
'PASSWORD' :'admin',
'HOST' :'',
'PORT' :'',
}
- 在models中每个类对应一个数据库表,多对多字段例外,Django专门建立了一张多对多关系表。
- 使用python manage.py check
检查项目有无问题。
#建立数据库版本备份,以便后面升级使用
#控制台中
python3 manage.py makemigerations
#同步数据库(在数据库中建表)
python3 manage.py migrate
#注册管理员账户
python3 manage.py createsuperuser
#在urls.py设置管理员路径
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
# 参考Django杂记中的
{% for ... in ...%}
{%if forloop.last %} ... {% endif %}
{% endfor %}
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def __unicode__(self): # __str__ on Python 3
return self.name
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
def __unicode__(self): # __str__ on Python 3
return self.name
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()
def __unicode__(self): # __str__ on Python 3
return self.headline
Author.objects.create(name:'eric',email:'[email protected]')
Author.objects.get_or_create(name:'eric',email:'[email protected]')
#返回(object , False/True)
# Person是已创建的一个模型且创建保存了一些实例化对象。
Person.objects.all() # 获取所有元素
Person.objects.all()[:10] #获取前十个元素
Person.objects.get(name='eric')
# 个人感觉元素筛选只需记住正则匹配即可(已验证)
Person.objects.filter(name_regex='^eric$') #查找name == 'eric' 的对象。区分大小写,name_iregex表示不区分大小写。
Person.objects.filter(name_regex='.*?eric.*?') #查找包含eric的对象
#排除某项为
Person.objects.exclude(name_regex='^eric$')
Person.objects.filter(name__contains="abc").exclude(age=23) # 找出名称含有abc, 但是排除年龄是23岁的
Person.objects.filter(name__contains="abc").update(name='xxx') # 名称中包含 "abc"的人 都改成 xxx
Person.objects.all().delete() # 删除所有 Person 记录
temp = Person.objects.get(name='eric')
temp.name = 'Eric'
temp.age = '21'
temp.save()#记得保存哦
Author.objects.all().order_by('name')#以名字为依据正序
Author.objects.all().order_by('-name')#以名字为依据倒序
Author.objects.filter(name__contains="eric").filter(email="[email protected]")
#错误啊,Querset API不支持负索引
Author.objects.all()[:-10]
#通过revrese解决
Author.objects.all().reverse()[:2] #获取倒数两项 / [0]获取最后一项
qs1 = Pathway.objects.filter(label__name='x')
qs2 = Pathway.objects.filter(reaction__name='A + B >> C')
qs3 = Pathway.objects.filter(inputer__name='WeizhongTu')
# 合并到一起
qs = qs1 | qs2 | qs3
这个时候就有可能出现重复的
# 去重方法
qs = qs.distinct()
# 编写兼容python2的代码
@python_2_unicode_compatible
''.join(str(random.choice(range(10))) for i in range(9))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
-在模块头加入如下代码
import django
import os
os.environ.update({"DJANGO_SETTINGS_MODULE": "ProjectName.settings"})#注意输入对象的项目名称,非应用名称
django.setup()
#输出sql语句
print(Author.objects.filter(name__regex='z'))
#以元组的形式输出结果
print(Author.objects.values_list('name','qq'))#以元组方式显示字段匹配结果
print(Author.objects.values_list('name',flat = True))#对于需要一个字段信息的查询以list形式输出
print(Author.objects.filter(name__regex='zh').values_list())#以元组形式输出过滤结果
print(Author.objects.filter(name__regex='^zhen$').values_list('qq',flat=True))#输出zhen作者的qq
# 获取字典形式的结果
print('==================================================')
print(Article.objects.values('title','tags'))#以字典形式输出字段匹配结果
print(Article.objects.values('title'))
print(Article.objects.filter(Author__name='twz915').values('title'))
# extra练习
print('==================================================')
print(Tag.objects.extra(select={'tag_name':'name'}).query)#SELECT (name) AS "tag_name", "blog_tag"."id", "blog_tag"."name" FROM "blog_tag"
print(Tag.objects.all().extra(select={'tag_name': 'name'}).defer('name').query)#SELECT (name) AS "tag_name", "blog_tag"."id" FROM "blog_tag"
python3 manage.py makemigrations
python3 manage.py migration
class Article(models.Model):
title = models.CharField(u'标题', max_length=256)
content = models.TextField(u'内容')
pub_date = models.DateTimeField(u'发表时间', auto_now_add=True, editable=True)
update_time = models.DateTimeField(u'更新时间', auto_now=True, null=True)
def __str__(self):
return self.title
admin.site.register(Article)
python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py createsuperuser
研究项目
- 在admin.py中增加后台需要显示的项目
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'pub_date', 'update_time',)
class PersonAdmin(admin.ModelAdmin):
list_display = ('full_name',)
admin.site.register(Article, ArticleAdmin)
admin.site.register(Person, PersonAdmin)
项目地址
- 创建forms.py
class AddForm(forms.Form):#表单里面有两项数据
a = forms.IntegerField()
b = forms.IntegerField()
def index(request):
if request.method =='POST':
form = AddForm(request.POST)#获取提交的表单数据,以字典的形式
#判断数据是否合法
if form.is_valid():
# 从字典里面取出值
a = form.cleaned_data['a']
b = form.cleaned_data['b']
return HttpResponse(str(int(a)+int(b)))
else:#如果浏览器不是post提交数据
form = AddForm()
return render(request,'index.html',{'form':form})
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.index),
]