TimeField returning None in Django - django

I have an existing database I need to pull data from the timestamp field in Django. I created the Django model as a TimeField, but when I query the data I get 'None' instead of the data in the timestamp field.
From my model class: (there is more in the model, I just condensed this for readability)
class Report(models.Model):
upload_time = models.TimeField()
date = models.CharField(max_length=9)
#staticmethod
def get_reports(**query):
reports = Report.objects.order_by('date').filter(query)
for report in reports:
print(report.upload_time)
In my views.py I have a method that checks for the date I am looking for to pull all reports from that date. The database saved the date as a string, so I get that ok, then just turn it into a datetime object and call my get_reports method by passing the date into it. It works to get everything from the report except the timestamp.
What am I missing?

Related

Serializing an SQL Function in Django REST

I'm using Django and Django Rest Framework to build an API.
I have a custom PostgreSQL function like this: myfunction(from_date, to_date)
It simply calculates a figure from records in the date range in reviews table.
How can I (safely!) take from_date and to_date from URL query parameters, pass them to the function, and return the (float) result via the API?
I have made a simple model to hold the float, like this:
class Result(models.Model):
result = models.FloatField(default=0)
class Meta:
managed = False
Alternatively, could I forgo the SQL function and implement this directly in Django/REST itself?
I already have a model for reviews. In the view for result can I pull reviews from a date range, calculate it, and return the value as a serialized result response?
As an end result, I want to be able to curl http://my.api/result?from=2019-03-01&to=2019-04-01 and get the result.
Thank you.
you can just simple filtering with lte and gte in your review Model and i am supposing date is a field of your Review model where you store record of every review. Then
Review.objects.filter(date__gte=from_date, date__lte=to_date)
Replace date with appropriate field name of your Review model And also with appropriate serializer.

saving date and time of user response in django model field

i am making this app in django where on a particular html template if the user selects a particular response by clicking on it, the date and time at which the user clicked that particular response is stored in my database.
part of models.py
class userresp(models.Model):
rid=models.Integerfield(unique=True,default=0)
uid=models.Foreignkey(user,to_field='uid',on_delete=models.CASCADE)
resp=models.ForeignKey(elementsound,to_field='csid',on_delete=models.CASCADE)
date=models.DateTimeField()
time=models.DateTimeField()
so how do i store that? and what will be the extra parameters in the DateTimeField of both?
You can do the what you require inside a View by overriding the post() method.
To store the user's response time, you can make use of django's builtin timezone module.
So you just need to do:
from django.utils import timezone
date_and_time = timezone.now()
timezone.now() returns the system date and time of the server.
And by the way, you don't need two 'DateTimeField's to store the date and time. One is enough, it can store both the date and time.
Otherwise you can just get the current date and time at the time of userresp object creation.
class userresp(models.Model):
rid=models.Integerfield(unique=True,default=0)
uid=models.Foreignkey(user,to_field='uid',on_delete=models.CASCADE)
resp=models.ForeignKey(elementsound,
to_field='csid',
on_delete=models.CASCADE)
date_and_time=models.DateTimeField(auto_now_add=True)

How to get time stamp of database update using psycopg2

I am implementing HTTP streaming with Django. When a user opens a webpage, there is a connection made to the server which returns back data when a new entry is made to the postgresql table.
Let's call the model "M", the model which when updated returns back the data to the client
I have a view get_update which does the timestamp checking and returns back data.
How can I go about doing it?
Without seeing your code it's hard to know, but from what I understand you're trying to query the last time a table was updated. If that's correct, I would just add a "last_updated" attribute on your model and query that, like so:
models.py
class YourModel(models.Model):
last_updated = models.DateTimeField(auto_now=True)
views.py
def get_update():
time_updated = YourModel.objects.last().last_updated
return(time_updated)

Django: date field saved to model but not retrieved

Django 1.9 / Python 2.7
Given this model:
class CoursePurchase(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
course = models.ForeignKey(Course)
date_purchased = models.DateField(default=date.today())
I would expect date_purchased to store the date I enter into Django admin, and it does, according to my database browser:
However, retrieving the object in the view has today's date instead of the stored date:
(Note the date_purchased field of __unicode__ returns today's date instead of the stored date.
Here is the code I'm using to retrieve the instance:
cp = CoursePurchase(course=page.course, user=request.user)
where course and user return the expected values.
What am I missing? This seems fairly straightforward, but I can't get past this.
To set the current date on save, django provides special arguments to the DateField type:
Django documentation:
class DateField(auto_now=False, auto_now_add=False, **options)
A date, represented in Python by a datetime.date instance. Has a few extra, optional arguments:
DateField.auto_now
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.
The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.
DateField.auto_now_add
Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True:
For DateField: default=date.today - from datetime.date.today()
For DateTimeField: default=timezone.now - from django.utils.timezone.now()
The default form widget for this field is a TextInput. The admin adds a JavaScript calendar, and a shortcut for “Today”. Includes an additional invalid_date error message key.
The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error.
But that's not the cause of the issue you see. When you do this:
cp = CoursePurchase(course=page.course, user=request.user)
You are not retrieving anything from the database, but rather creating a new instance (in-memory only, not saved anywhere yet). To retrieve instances, you need to query the database properly:
cp = CoursePurchase.objects.get(course=page.course, user=request.user)
You can try like this.
cp = CoursePurchase.objects.get(course=page.course, user=request.user)

Django - Date and Time Field Explanation

I have few questions regarding the Date and time fields both in the model and in the form class.
1.)In the docs for the date field what does the line "Normalizes to: A Python datetime.date object." mean? Does it mean that the field data stored in the request.POST dictionary on the submission of the form is a datetime.date object?If yes, then when does it do it when the form is submitted or do we have to call one of its functions?
2.)If i have a models.DateField() then while assigning data to it manually in a view should i assign a datetime.date object or a unicode object with the 'yyyy-mm-dd' format?
3.)If i take a date in my forms.DateField() in the '%d/%m/%y' format how do i assign it to my models.DateField() because that seems to accept only the 'YYYY-mm-dd' format?
If somebody could also suggest some links which explain these fields in detail with examples apart from the docs it would be helpful.
For first question, datefield saves date object and if you are saving any data( for example a string: "01-01-2015") to datefield, then you have to convert that data into date object. You will not get a date object in request.POST, if you use a form, then you can get it by using cleaned_data.(example below) From request.POST ,you will get an unicode object.( then you will need to convert it to date object, example below)
For second question, obviously you have to save dateobject, not unicode object.
For third question, in forms, To display initial field value properly formatted, use DateInput widget. To customize validation, use input_formats keyword argument of DateField. Here, from forms, you will get a date object in views, so it can be saved directly, like:
In model.py:
class DateModelClass(models.Model):
date= models.DateField()
In forms.py:
date= forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=('%d/%m/%Y',))
In views.py:
date_data= DateModelClass(date= form.cleaned_data['date'])
date_data.save()
Also you can convert a string of your desired format to Date Object like this:
>>import datetime
>>datetime.datetime.strptime(u"09/07/2014", '%d/%m/%Y').date()