Im having a trouble how to set default date in my models, the format should I have in my database is date not datetime but the resources mostly I find is the code below, Is there any way how to set my models into date? Thanks in advance!
The output/format saved in database should like this
2020-11-24
Format of my date in sql
from datetime import datetime
class Person(models.Model):
date_upload = models.DateTimeField(default=datetime.now().strftime ("%Y-%m-%d"), blank=True)
you should try like this:
from datetime import date
class Person(models.Model):
date_upload = models.DateTimeField(default=date.today(), blank=True)
If you just want the date in the database, without the time, use DateField.
Then just use date.today as the default for the field. Since date.today is a callable, it will call this method each time a new instance of this model is created.
from datetime import date
class Person(models.Model):
date_upload = models.DateField(default=date.today, blank=True))
You can also just use auto_now or auto_now_add to automatically set it to today:
# Set on creation and additional saves
date_upload = models.DateField(auto_now=True, blank=True))
# Only set on creation
date_upload = models.DateField(auto_now_add=True, blank=True))
Related
I have a model
class Session(models.Model):
name = models.CharField(max_length=12)
active = models.BooleanField(default=False)
date = models.DateField()
startTime = models.TimeField()
The active field is set based on the date and start time.
For eg -
Suppose during the creation of an object, the date is for tomorrow, and let there be any time, I want to know the process and not the code on how and what to study to make this object active on that particular date and time.
BY default the active field is False, or should I change the way I'm thinking to implement it?
Thanks
I would advise to use a DateTimeField for the start timestamp, and make active a property, so:
from django.utils import timezone
class Session(models.Model):
name = models.CharField(max_length=12)
start = models.DateTimeField()
#property
def active(self):
return timezone.now() >= self.start
This will thus not store the active field in the database, but simply determine the value when needed.
I'm using timezone.now() (django.utils impor timezone) to set the initial date of my model. But, the timezone.now() is fixed to the time when i set the server up, and doesnt change. How can i fix this?
I wanna that the timezone.now() return the datetime when the user is creating an object and not the time when i run the server.
You should pass a reference to the function to it, so:
from django.db import models
from django.utils import timezone
class MyModel(models.Model):
created_at = models.DateTimeField(default=timezone.now)
But likely you want to use auto_now_add=True [Django-doc], which will also make the field non-editable:
from django.db import models
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
I have a model with a models.DateTimeField field and a CheckConstraint that prevents it from being in the past:
from django.db.models.functions import Now
class MyModel(models.Model)
title = models.CharField()
mydate = models.DateTimeField()
class Meta:
models.CheckConstraint(
check=Q(mydate__gte=Now()),
name='mydate_no_past'
),
I want the constraint to apply only when the record is first created, ideally using Django and not raw SQL (per this answer).
In the above example, if a valid entry is created but then later the system datetime moves past the mydate value, when the record is updated the CheckConstraint fails.
How do I avoid this?
What also confuses me is if I update only other fields on the record and not mydate the CheckConstraint still fails. E.g the following will also fail if the system date is after the mydate value:
mymodel = MyModel.objects.get(pk=1)
mymodel.title = 'Title'
mymodel.save(update_fields=['title'])
Why is this?
I have a model where I want the name field to be a string representation of the timestamp, and another field to be the actual time stamp. Here is my model code:
from django.db import models
from datetime import datetime
class Image(models.Model):
name = models.CharField(max_length=255, default=datetime.now().strftime("%Y%m%d-%H%M%S"))
create_date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to="images/")
Then I go in the django shell and enter this:
>>> import models
>>> models.Image(image='images/rock.png').save()
This works but the only problem is the two times do not align. For example, I get name = 20191201-143119 and create_date = 2019-12-01 14:32:11.445474.
How can I get these two datetimes to be the same?
This is a pretty common gotcha in Django's world. The post mentioned by #eliakin-costa discuss this problem, although his solution works I wouldn't recommend overriding save method to get this behavior as it's easier to create a function (keeping decoupled and explicit):
from django.db import models
from django.utils import timezone
def default_image_name():
return timezone.now().strftime("%Y%m%d-%H%M%S")
class Image(models.Model):
name = models.CharField(max_length=255, default=default_image_name)
create_date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to="images/")
By the way, did you take a look at this docs (upload_to also accepts a callable) ? Do you really need a name column in your table?
I've linked an answer will help you understand what is happening. Achieving what you want is quite simple though.
models.py
from django.db import models
from datetime import datetime
class Image(models.Model):
name = models.CharField(max_length=255)
create_date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to="images/")
def save(self, *args, **kwargs):
if not self.name:
self.name = datetime.now().strftime("%Y%m%d-%H%M%S")
super(Image, self).save(*args, **kwargs)
Consider the following model. I'd like to filter objects based on the latest timestamp, which might be either created_at or updated_at. For some reason, the filter function does not recognise the annotated field and I'm having hard time finding the appropriate code examples to do this simple thing.
The error message is "Cannot resolve keyword 'timestamp' into field.".
How would you retrieve the Example objects within 7 days, based on newer date.
from datetime import timedelta
from django.db import models
from django.db.models.functions import Greatest
from django.utils import timezone
class Example(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True)
#property
def recently_updated(self):
return Event.objects
.annotate(timestamp=Greatest('created_at', 'updated_at'))
.filter(timestamp__gte=timezone.now() - timedelta(days=7))
.order_by('-timestamp')
Django 1.11
Just set updated_at = models.DateTimeField(auto_now=True, null=True), this way when record is inserted for the first time updated_at and created_at will be same, so, you can just run the query on updated_at:
Event.objects.filter(updated_at__gte=timezone.now() - timedelta(days=7)).order_by('-timestamp')