Search between two dates in Django

Asked

Viewed 100 times

-1

I have a program where I need to search through GET on Django the data present between two dates (the user will define these dates)

Models py.

class Data(models.Model):
    dev = models.ForeignKey(Device, on_delete=models.CASCADE,related_name="data")
    voltage = models.CharField(max_length=255)
    current = models.CharField(max_length=255)
    active_power = models.CharField(max_length=255)
    reactive_power = models.CharField(max_length=255)
    temperature = models.CharField(max_length=255)
    dev_energy = models.CharField(max_length=6)
    dev_on = models.BooleanField(default=True)
    time = models.DateTimeField(max_length=70)

class Meta:
    verbose_name = 'data'
    verbose_name_plural = 'datas'

def __str__(self):
    return f'Datas'

Views.py

class DataViewSet(ModelViewSet):
#queryset = Data.objects.all()
queryset = Data.objects.filter(time__range=[data_inicio, data_final])
serializer_class = DataSerializer

Urls.py

urlpatterns = [
url(r'data/$', views.Data.as_view(), name='data'),
url(r'data/(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})/$',
    views.Data.as_view(), name='filter_data'),

]

I need to adjust the views so that the parameters data_start and data_final are passed through the url, but I only found how to pass only one of the parameters through it. That’s possible?

2 answers

0


Based on comments and post editing:

Generally speaking, there are three ways to pass data to a view:

  1. In the URL path (eg.: https://www.seu_site.com.br/livros/10)
  2. As argument in the URL (eg.: https://www.seu_site.com.br/livros?identificador=10)
  3. No body of the REST request - Will not be described in this reply

Using the path

urls.py

from django.urls import path

urlpatterns = [
    path('livros/<int:identificador>/', views.livros, name='os_livros'),
]

views.py

def livros(request, identificador):
    # sua lógica aqui

Using as argument

urls.py

from django.urls import path

urlpatterns = [
    path('livros/', views.livros, name='os_livros'),
]

views.py

def livros(request):
    identificador = requests.GET.get('identificador')
    # sua lógica aqui

Your case

In your case, I would use the second form.

Something like: https://www.seu_site.com.br/data?inicio=1/1/2021&fim=31/1/2021

Its url would be: path('data/', views.sua_view, name='sua_view_name')

In.py views you would have:

def sua_view(request):
    data_inicio = requests.GET.get('inicio')
    data_fim = requests.GET.get('fim')
    # sua lógica aqui

Note Values are received as a string and should be converted to the desired format if necessary

I hope it helps

-2

Simple:

Data.objects.filter(time__range=(data_inicial, data_final))

Elegant:

class Data(models.Model):
    dev = models.ForeignKey(Device, on_delete=models.CASCADE,related_name="data")
    voltage = models.CharField(max_length=255)
    current = models.CharField(max_length=255)
    active_power = models.CharField(max_length=255)
    reactive_power = models.CharField(max_length=255)
    temperature = models.CharField(max_length=255)
    dev_energy = models.CharField(max_length=6)
    dev_on = models.BooleanField(default=True)
    time = models.DateTimeField(max_length=70)

    objects = DataManager()

    def __str__(self): 
        return f'Datas'

    class Meta:
        verbose_name = 'data'
        verbose_name_plural = 'datas'
class DataManager(models.Manager):
    def entre_datas(self, data_ini, data_fim):
        self.filter(time__range=(data_ini, data_fim))

Data.objects.entre_datas(<DATA_INICIAL_AQUI>, <DATA_FINAL_AQUI>)

I hope it helps

  • Data.objects.filter(time__range=(initial data_final)) I put in the data manager view?

  • Datamanager is part of Model (models.py). Are you looking to form, view and template for data recovery? If so, take a look at it here

  • Actually I would like to do only View, I’ve been working on Jango for a while and I still haven’t touched the form and template

  • Look at the link I passed, has the views.py there.

  • Thanks for the help, I adjusted the models according to the "elegant" way, but I still could not tidy up the views even with the link I’m having difficulties to apply to my example

  • I suggest putting all the important files in your project: urls.py, models.py, views.py in a new post and explaining what you want exactly.

  • For those who voted negative, could you tell me why I should improve the answer? I believe my answer answered the topic "Do a search between two dates in Django"

  • I edited and placed the views and urls to give an idea of what I need

  • Responded to comments in a different response.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.