读取数据库的数据:
sales/views.py :
定义一个listcustomers函数:
#导入:
from django.http import HttpResponse
#定义一个函数用于实现读取数据库里的数据:
def listcustomers(request):
#返回一个QuerySet对象,包含所有表记录
#每条表记录都是一个字典对象
qs=Customer.objects.values()
retStr=''
for customer in qs:
for key,values in customer.items():
retStr+=f'{key}:{values} | '
retStr+='<br>'
return HttpResponse(retStr)
sales/urls.py:
from django.urls import path
from sales.views import listorders1,listcustomers
urlpatterns = [
path('orders1/',listorders1),
path('customers/',listcustomers)
]
过滤条件读取数据库的数据(返回带参请求):
sales/views.py:
from django.shortcuts import render
from common.models import Customer
# Create your views here.
from django.http import HttpResponse
def listorders1(rsquest):
return HttpResponse('我是1')
def listcustomers(request):
#返回一个QuerySet对象,包含所有表记录
#每条表记录都是一个字典对象
qs=Customer.objects.values()
#检查url中是否有参数phonenumber(获取参数)
id=request.GET.get('id',None)
ph=request.GET.get('phonenumber',None)
#如果有,添加过滤条件:
if ph:
qs=qs.filter(phonenumber=ph)
if id:
qs=qs.filter(id=id)
#定义返回html字符串:
retStr=''
for customer in qs:
for key,values in customer.items():
retStr+=f'{key}:{values} | '
retStr+='<br>'
return HttpResponse(retStr)