Django Store date only or query with date only - django

My requirement is, every year the post should be found by user with a specific date range. in end_date and state_date
So i want to store only date or i have to query by date only instead of year
But i found no way to do that, coz, it is storing year too
class Post(models.Model):
title = models.CharField(max_length=255, null=True)
start_date = models.DateField(null=True, blank=True)
end_date = models.DateField(null=True, blank=True)
I have tried to query like this:
post = Post.objects.filter(
start_date__gte='09-16',
end_date__lte='10-01'
)
but above solution doesnt work well, any have ideas how can i do it? storing date only except year or query by date only?, so that it works every year without any hassle

You can try this:
post = Post.objects.filter(
start_date__day__gte=16, start_date__month__gte=9,
end_date__day__lte=10, end_date__month__lte=1
)
Basically, you use day, month and year with DateField and DateTimeField the same way you use eq, lt etx.

Related

wanted to filter all the records created in last 24 hours with Django filter but timestamp stored epoch format in CharField

problem context - I've a django model like this.
class UpdateRequests(models.Model):
field_name = models.CharField(max_length=20)
field_new_value = models.CharField(max_length=20)
created_at = models.CharField(max_length=10)
customer_id = models.CharField(max_length=50)
request_status = models.CharField(max_length=20, choices=JOS_STATUS)
request_close_date = models.CharField(max_length=20)
problem statement - I want to fetch all records created with in last 24 hours.
how I was trying - I was trying like this in my view function
time_threshold = datetime.now() - timedelta(days=1)
results = UpdateRequests.objects.filter(created_at__lte=time_threshold,
request_status="Pending").values()
but it is not working and I guess because django __lte , __gte works on DateTimeField() only.
reference - https://docs.djangoproject.com/en/4.1/ref/models/querysets/
Please help me with this, I don't want to change the schema since it's already in the production.
Bruh you stored datetime in charfield created_at = models.CharField(max_length=10) How can db serve you Datetime Object? you have to make changes in Models and create objects again with this
created_at = models.DateTimeField(null=True,blank=True,auto_now_add=True)
auto_now_add=True Will fetch current datetime when you will Create Model object.

Applying date filter on a char-field that stores the date-time in string in django?

I have this field on a model X:
class Details(models.Model):
start_time = models.CharField(max_length=25, null=True, blank=True)
Now, one problem arises that I need to apply the date filter on this. is there any way to solve this.
Now due to this the datetime is getting stored like this is db
Start time
2021-12-03T13:00:00Z
I want to do something like this-
Details.objects.filter(start_time__time=some_time)

Django filter problem with date calculation

Django model has birth_year, birth_month, birth_day and death_year, death_month, death_day fields.
model.py
class person(models.Model):
birth_year = models.SmallIntegerField()
birth_month = models.SmallIntegerField()
birth_day = models.SmallIntegerField()
death_year = models.SmallIntegerField()
death_month = models.SmallIntegerField()
death_day = models.SmallIntegerField()
I have to get the count of persons who lives less than 1 month.
views.py
return render(request, 'report.html', {'count': count})
how can I query in view.py
I hope django expert's help. :)
I have to get the count of persons who lives less than 1 month.
Use DateField:
class Person(models.Model):
birth = models.DateField()
death = models.DateField()
You can use F expressions to do the calculation, like this:
from datetime import timedelta
from django.db.models import F
q = Person.objects.annotate(life_span=F('death') - F('birth'))
.filter(life_span__lte=timedelta(days=29))
.count()
print(f'Number of people {q}')
Here I am assuming anyone who lives less than 29 days to have lived for less than a month.
The concept of a "month" differs based on leap years, etc. If you need that kind of precision, you can add some more filters and logic to the above.

Django: Give date field default value of one month from today

In Django, you can have a date field and set the default value to today.
start_date = models.DateField(default=timezone.now, blank=True, null=True)
How do you set the default date to 1 month from today?
You can use any callable as a default value, so that should work:
from datetime import timedelta
def one_month_from_today():
return timezone.now() + timedelta(days=30)
class MyModel(models.Model):
...
start_date = models.DateField(default=one_month_from_today, blank=True, null=True)
Note that I used days=30 as timedelta can't add a month to a date value. If you think of it, "one month from today" is a pretty open statement (how do you want it to behave when today is January 31, for example?).

Django Queryset - filter "before end date" if existing

I have model that use to don't have DateField, now I'm migrating it with "south"; and I'm adding a "start_date" and "end_date" to it:
class MyModel(models.Model):
my_attribute = models.CharField(max_length=100)
start_date = models.DateField(default = date.today)#Newly added field
end_date = models.DateField(blank=True, null=True)#Newly added field
For the existing records on the database (and the future ones) the start_date will be by default set to today's date, the old records will not have an end_date, and future ones may have a blank end_date if not specified.
My need: Given a DATE:
Filter objects from DB, that DATE is between start_date and end_date if the object has both start and end date (e.g: MyModel.objects.filter(start_date__lte=DATE, end_date__gte=DATE)
Filter objects from DB, that DATE is newer than start_date if the object has blank (or null) end_date
Is my migration correct ?
Which queryset should I perfprm to accomplish my need.