saving submission.created_utc value and saving in django models.DateTimeField - django

Having an issue grabbing the submission.created_utc value and trying to store it in my django models.DateTimeField.
// here's my model's DateTimeField
red_created = models.DateTimeField(default=timezone.now, editable=False)
// this is how I try to save it
red_created = returnUtcDate(submission.created_utc)
// value of created_utc = 1589720741.0
def returnUtcDate(utcDate):
dt = datetime.fromtimestamp(int(utcDate))
newUtcDate = timezone.make_aware(dt, timezone.utc)
return newUtcDate // value being returned 2020-05-17 13:05:41+00:00
When I try to run that I get:
TypeError: expected string or bytes-like object
I know I need to convert the utc date before I store it but I don't know how or to what format. Tried searching but I'm assuming searching for the wrong terms.

Related

Django ORM update field to NOW() returning 0 error

I am trying to loop through a list of results, process them, then update their "updated_details" field.
users_to_update = TiktokUser.objects.filter(Q(updated_details__lt=datetime.utcnow() - timedelta(weeks=1)) | Q(updated_details__isnull=True))[0:1]
for user_to_update in users_to_update:
print(datetime.now())
user_to_update.updated_details = datetime.now()
user_to_update.save()
The idea being that on each loop, i set the updated_details to the current timestamp. My print() statement here correctly prints out the current date and time, however when I update the record itself and save, I get the following error:
['“0000-00-00 00:00:00.000000” value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time.']
Which implies to me it is attempting to set it to 0.
My model definition is:
class User(models.Model):
...
updated_details = models.DateTimeField(blank=True, null=True)
...
How do I get Django to set the field to the current DateTime?
You are using python datetime, please use django datetime it's based upon settings file of your django project
from django.utils.timezone import now
users_to_update = TiktokUser.objects.filter(Q(updated_details__lt=datetime.utcnow() - timedelta(weeks=1)) | Q(updated_details__isnull=True))[0:1]
for user_to_update in users_to_update:
user_to_update.updated_details = now()
user_to_update.save()

What is proper way to store data in DateTimeField field

I have a model Fixture
Class Fixture(models.Model):
event_timestamp = models.DateTimeField(null=True)
I have piece of json data
for item in piece_json:
event_timestamp = item["event_date"]
Where in item["event_timestamp"] the following data 1572567600
While i am trying to create object from this model
fixture = Fixture.objects.create(event_timestamp= event_timestamp)
I got the following error
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
After this error i tried to wrap event_timestamp variable in built-in str() function
fixture = Fixture.objects.create(event_timestamp= str(event_timestamp))
After it i got error
django.core.exceptions.ValidationError: ["'1572651000' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
I don't think DateTimeField allowsyou to save Unix Timestamp.
What I can suggest you do is:
import datetime
fixture = Fixture.objects.create(event_timestamp=datetime.datetime.utcfromtimestamp(event_timestamp))

Why Django DateField doesn't accept empty values?

I have a model with a DateField field with blank = True and null = True.
It seems that is not possibile save an object with an empty value for the Datefield.
class ProjectTask(models.Model):
actual_start_date = models.DateField(blank=True, null=True)
Then try with Python console:
p = ProjectTask.objects.all().last()
p.actual_start_date = ""
p.save()
The results is:
venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1273, in to_python
params={'value': value},
django.core.exceptions.ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."]
I'm using Python 3.4, Django 1.9 and PostgreSQL.
Any suggestions?
Dates are not strings. If you want to pass a string, it needs to be converted to a date. Normally, your form would validate whether or not you had a valid date, but you've bypassed this by setting an empty string directly on the model.
If you don't want to set a value at all, then pass None.

Getting value of a ForeignKey instead ID

I have to pass a ForeignKey object in a json response, im doing it like this:
data = {}
p = Bets.objects.create( bet_id=request.POST['team'],number=number)
data['success'] = p
return HttpResponse(json.dumps(data), content_type='application/json')
bet_id field is a ForeignKey and number is a CharField, if in data['success'] I pass p.number i can pass it with no troubles, but when I pass p.bet_id I get the id of that ForeignKey, I need to get the value, I'm trying with lookup fields with p.bet_id__name but i get the following error:
'Bets' object has no attribute 'bet_id__name'
My models:
class Teams(models.Model):
name = models.CharField(max_length=100)
class Bets(models.Model):
bet = models.ForeignKey(Teams)
number = models.CharField(max_length=255)
how can I achieve get the value instead the id?
You'll want to use:
data['success'] = p.bet.name
Note that this will create a second SQL query against your db to load the Team object tied to p.bet. To save yourself a little bit of overhead, you can change this line:
Bets.objects.create( bet_id=request.POST['team'],number=number)
To this:
Bets.objects.create( bet_id=request.POST['team'],number=number).select_related('bet')

Django QuerySet: Is it possible to filter for field__is_null for FloatFields?

I want to be able to query a model for records where the is no value for a particular float field. The problem is the basic query:
Model.objects.filter(float_field__is_null=True)
returns the following error: django.core.exceptions.FieldError: Unsupported lookup 'is_null'.
To test, create the following model:
class FloatFieldModel(models.Model):
date = models.DateField()
val = models.FloatField(blank=True, null=True)
Then:
>>> objects = FloatFieldModel.objects.filter(val__is_null=True)
>>> django.core.exceptions.FieldError: Unsupported lookup 'is_null' ...
How can I filter a model for records where there is no value for a particular float field? In other words, what is the best work around?
What I want to be able to do is the set up a routine to only update rows without any values, but skip those rows already with a specified value (while making most efficient use of my database). What I was trying looks something like:
for date in dates:
try:
FloatFieldModel.objects.filter(
date=date,
val__is_null=True
).update(val=42.0)
except FloatFieldModel.DoesNotExist:
pass
I imagine I could do something like:
objects = FloatFieldModel.objects.all()
for obj in objects:
if obj.val is None and obj.date in set(dates):
obj.val = 42.0
obj.save()
I was trying for a more efficient process though, rather than on which required reading each object from the database into memory before saving.
There is lookup isnull not is_null https://docs.djangoproject.com/en/dev/ref/models/querysets/#std:fieldlookup-isnull
Model.objects.filter(float_field__isnull=True)