day7

三方库bpmapper的使用

from bpmappers import RawField, DelegateField,Mapper
from bpmappers.djangomodel import ModelMapper
from record.models import Record

# 只取需要的carno和owner属性
class CarMapper(Mapper):
    carno= RawField()
    owner= RawField()

# 多对一使用DelegateField
class RecordMapper(ModelMapper):
    # 多对一
    car = DelegateField(CarMapper)
    makedate = RawField()
    # 原始字段
    @staticmethod
    def filter_makedate(makedate):
        return makedate.strftime('%Y-%m-%d %H:%M')

    class Meta:
        model = Record

删除数据库表格

删除django迁移记录 ,删除表,删除数据库migrations 表记录

前端渲染

views视图函数获取数据

def search(request):
# 从模板页获取carno 页码
    carno = normalize(request.GET.get('carno',''))
    current_page = int(request.GET.get('page','1'))
    if carno:
        # 外键列关联查询
        queryset = Record.objects.filter(
                Q(car__carno=carno) | Q(car__owner__contains=carno)
            )
    else:
        queryset = Record.objects.all()
    queryset = queryset.select_related('car').order_by('-makedate')
    records,total_page = [],0
    try:

        paginator = Paginator(queryset,5)
        total_page = paginator.num_pages


        for record in paginator.page(current_page).object_list:
            records.append(RecordMapper(record).as_dict())
    except EmptyPage:
        pass
    return JsonResponse({'code':200,
                         'currentPage':current_page,
                         'totalPage':total_page,
                         'records': records
                         })
# vue获取json数据,绑定点击事件查询
const app = new Vue({
           el: '#app',
           data: {
               records: [],
               carno: '',
               currentPage: 1,
               totalPage: 0,
               loaded: false
           },
        methods: {
               getData() {
                   let carno = this.carno.trim()
                   fetch(`/search/?carno=${carno}&page=${this.currentPage}`)
                       .then(resp => resp.json())
                       .then(json => {
                           this.records = json.records
                           this.currentPage = json.currentPage
                           this.totalPage = json.totalPage
                       })
               },
change() {
                   this.loaded = false
               },
       search() {
                   this.currentPage = 1
                   this.totalPage = 0
                   this.getData()
                   this.loaded = true

               },

你可能感兴趣的:(day7)