How to query data within a certain period of time with Vue front-end and Django back-end

How to query data within a certain period of time with Vue front-end and Django back-end

Preface

During the development process, you will often encounter functions such as filtering queries, such as querying data within a certain time period instead of all data.

In this way, we need to send the time period parameters to the backend, and then process the query on the backend.

Here we use a simple example of Django backend and Vue frontend to record the general implementation.

Backend database

Here are some simple data. The important thing is the date. We need to filter and return it to the front end based on the date.

models.py

class CountDownSign(models.Model):
 name = models.CharField(max_length=1000) 
 date = models.DateField() 
 sign = models.CharField(max_length=200) 

serializers.py

The drf framework is introduced here, but the idea of ​​filtering queries has nothing to do with this framework.

class CountDownModelSerializer(serializers.ModelSerializer):
 class Meta:
 model = CountDownSign
 fields = '__all__'

 def create(self, validated_data):
 return CountDownSign.objects.create(**validated_data)

 def update(self, instance, validated_data):
 instance.name = validated_data.get('name', instance.name)
 instance.date = validated_data.get('date', instance.date)
 instance.sign = validated_data.get('sign', instance.sign)
 instance.save()
 return instance

views.py

Provides an interface for filtering queries. Get the start and end dates delivered by the front end. The core code is as follows

obj = models.CountDownSign.objects.filter(date__range=(start, end))
class CountDownViewSet(ModelViewSet):
 parser_classes = [JSONParser, FormParser]
 """ViewSet"""
 queryset = models.CountDownSign.objects.all()
 serializer_class = CountDownModelSerializer
 # Search search_fields = ('id', 'name', 'sign', 'date')
 
 @action(methods=['post'], detail=False)
 def getSE(self, request, *args, **kwargs):
 start = request.data.get('start', None)
 end = request.data.get('end', None)
 if start and end:
  obj = models.CountDownSign.objects.filter(date__range=(start, end))

  if obj:
  ser = CountDownModelSerializer(instance=obj, many=True)
  print(ser.data)
  return JsonResponse({
   'code': '200',
   'msg': 'Get data successfully',
   'data': ser.data
  })
  else:
  return JsonResponse({
   'code': '1002',
   'msg': 'Get failed',
  })
 else:
  return Response(status=status.HTTP_204_NO_CONTENT)

Front-end interface

Here are two date-pickers for receiving the start and end time, and binding events for the search.

 <div class="datePicker">
 <div class="block" style="float: left">
 <el-date-picker
  v-model="value1"
  type="datetime"
  value-format="yyyy-MM-dd"
  placeholder="Please select a start date">
 </el-date-picker>
 </div>
 <div class="block" style="float: left; margin-left: 20px;">
 <el-date-picker
  v-model="value2"
  type="datetime"
  value-format="yyyy-MM-dd"
  placeholder="Please select a deadline">
 </el-date-picker>
 </div>
 <el-button round style="float: left; margin-left: 20px;" @click="searchC">Search</el-button>
 </div>

data.js

Implemented interface functions

export function searchCountDown(start, end) {
 return request({
 url: 'countDown/getSE/',
 method: 'post',
 data: {
  start: start,
  end: end
 }
 })
}

Click event implementation

Determine the legitimacy of the input and accept the data for data binding display

searchC() {
 console.log(this.value1);
 console.log(this.value2);
 if (this.value1 < this.value2) {
 searchCountDown(this.value1, this.value2).then(res => {
  console.log(res.data);
  this.searchRes = res.data;
 })
 } else {
 this.$message.error("Time range error");
 }
 },

Data display

 <div class="article">
 <ul>
 <li v-for="(item,index) in searchRes">
  <div class="ui grid" style="width: 100%;height: 60px;">
  <div class="four wide column"><span>{{ item.name }}</span></div>
  <div class="four wide column"><span>{{ item.date }}</span></div>
  <div class="four wide column"><span>{{ item.sign }}</span></div>
  <div class="four wide column">
  <el-button type="danger" icon="el-icon-delete" circle @click="deleteC(item.id)"></el-button>
  <el-button type="primary" icon="el-icon-edit" circle></el-button>
  </div>
  </div>
  <div class="ui divider"></div>
 </li>
 </ul>

Operation Results

It can be seen that the returned data are all within the time range. Here, the data returned at 0:00 on February 25th is actually the data of February 5th. Because the data is formatted, the data of the 25th is also returned.

Summarize

This is the end of this article about how to query data within a certain period of time with Vue front-end and Django back-end. For more relevant Vue and Django data query content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Perfect solution to the conflict between Django and Vue syntax
  • Example of building a front-end and back-end separation project with Django+Vue.js
  • How to implement data interaction between Django and Vue
  • Methods and steps for data interaction using Django and Vue
  • Django+Vue cross-domain environment configuration detailed explanation

<<:  MySQL NULL data conversion method (must read)

>>:  Example of how to configure multiple virtual hosts in nginx

Recommend

Summarize the User-Agent of popular browsers

1. Basic knowledge: Http Header User-Agent User A...

UDP connection object principle analysis and usage examples

I wrote a simple UDP server and client example be...

VMware Workstation Installation (Linux Kernel) Kylin Graphic Tutorial

This article shares with you how to install Kylin...

mysql5.7.19 zip detailed installation process and configuration

MySQL v5.7.19 official version (32/64 bit install...

Implementing a simple student information management system based on VUE

Table of contents 1. Main functions 2. Implementa...

MySQL 8.0.21 installation and configuration method graphic tutorial

Record the installation and configuration method ...

Bootstrap 3.0 study notes page layout

This time we will mainly learn about layout, whic...

HTML embed tag usage and attributes detailed explanation

1. Basic grammar Copy code The code is as follows...

Implementation of remote Linux development using vscode

Say goodbye to the past Before vscode had remote ...

Solve the cross-domain problem of get and post requests of vue $http

Vue $http get and post request cross-domain probl...

Detailed explanation of the frame and rules attributes of the table in HTML

The frame and rules attributes of the table tag c...

Summary of using the reduce() method in JS

Table of contents 1. Grammar 2. Examples 3. Other...

Learn MySQL database in one hour (Zhang Guo)

Table of contents 1. Database Overview 1.1 Develo...

The button has a gray border that is ugly. How to remove it?

I used the dialog in closure and drew a dialog wit...

How to add java startup command to tomcat service

My first server program I'm currently learnin...