I am using django build in User model have one-to-one relation with UserProfile model. I have to count number of signups in a week. How can I do this?. Thanks in advance for your addition.
you can use date_joined in User model, it mean A datetime designating when the account was created. Is set to the current date/time by default when the account is created.
from datetime import datetime, timedelta
today = datetime.date.today()
startDate = today - datetime.timedelta(days=7)
endDate = today + datetime.timedelta(days=1)
users = User.objects.filter(date_joined__range=[startDate, endDate])
Related
I want to update the date from the backend views in django how can i did that here are my views where i want to do this
explaining what i exactly want to achive i am building a crm where clients suppose to pay monthly or quaterly depends on their plan i have given a button at dashbord which triggers this function and redirect to homepage in this function if the user date month came then this function is suppose to generate the bills which is fetching in the homepage and show outstanding amount what wrong happen with this idea everytime pressing the button it will genertate duplicate bills adding in revenue to stops this i add a variable is eligible which i thought the user will change it manually but then i feel it is more good to update the date
def refresh_dashboard(request):
date = datetime.datetime.now().strftime ("%Y%m%d")
m = datetime.date.today()
print(f"the date is {m}")
customer = Customer.objects.all()
for i in customer:
# print(i.eligible)
period = i.next_payment.strftime("%Y%m%d")
if period <= date and i.eligible == True:
x = Bill.objects.create(name = i.name,status ="unpaid",price = i.recuring_amount,generate_date = date)
x.save()
obj = i
# obj.next_payment.strftime("%Y%(m+1)%d")
obj.eligible = False
obj.save()
# print(f"the date is {date} and the obtain from the customer is {period}")
# print(f"this customer {i.name} bill need to be generated")
# print(f"the date is {datetime.datetime.now()}")
return redirect('/')
You can increment datetime on the basis of given days using timedelta
from datetime import datetime
from datetime import timedelta #new
today = datetime.now()
print(f"Today's the date & Time is {today}")
month_later = today+ timedelta(days=MONTHLY_CYCLE)
three_months_later = today+ timedelta(days=QUA_CYCLE)
six_months_later = today+ timedelta(days=SIX_MONTH_CYCLE)
print(f"three_months_later's the date & Time is {month_later}")
print(f"three_months_later's the date & Time is {three_months_later}")
print(f"six_months_later's the date & Time is {six_months_later}")
customer = Customer.objects.get(pk=id) # Targeted Customer
selected_cycle = int(customer.billing_cycle) #return the value of billing_cycle selected from Customer
tentative_date = today+ timedelta(days=selected_cycle)
print(f"tentative_date Billing date & Time is {month_later}") # Required DAte.
This is how you can update the datetime. rest you can implement as required.
I have a model like this
class Tasks(models.Model):
title = models.CharField(max_length=100,null=True,blank=True)
due_date_time= models.DateTimeField(default=timezone.now)
As due date is a date and time field, how I can check if today is due date of this task , while I am saving time and date both
You can make use of the __date lookup [Django-doc]:
from django.utils.timezone import now
Tasks.objects.filter(
due_date_time__date=now().date()
)
or if you work with timezones, you can work with a range check:
from datetime import timedelta
from django.utils.timezone import now
today = now().replace(hour=0, minute=0, second=0, microsecond=0)
tomorrow = today + timedelta(days=1)
Tasks.objects.filter(
due_date_time__gte=today,
due_date_time__lt=tomorrow
)
Note: normally a Django model is given a singular name, so Task instead of Tasks.
I'm trying to write a Django query for orders that when added 5 hours 30 minutes satisfy the condition,created_at is datetime
SELECT id, created_at + time '5:30' as created_at , date(created_at + time '5:30') as created_date
FROM orders WHERE date(created_at + time '5:30') > today_date
How to convert this into Django ORM ?
I assume that TIME_ZONE in setting is set to 'Asia/Kolkata' (i.e. UTC+5:30). If you have this setting, you can use django's timezone module.
Let's say the model name in 'Order'. The above query will be like this in ORM form:
from django.utils import timezone
orders = Order.objects.filter(created_at__gt=timezone.now().date())
And to convert the date got from this query into your timezone:
order = orders.first()
created_at = timezone.localtime(order.created)
If I have a Django Employee model with a start_date and end_date date field, how can I use get in the ORM to date effectively select the correct record if different versions of the record exist over time based on these date fields?
So I could have the following records:
start_date, end_date, emp
01/01/2013, 31/01/2013, Emp1
01/02/2013, 28/02/2013, Employee1
01/03/2013, 31/12/4000. EmpOne
And if today's date is 10/02/2013 then I would want Employee1.
Something similar to:
from django.utils import timezone
current_year = timezone.now().year
Employee.objects.get(end_date__year=current_year)
or
res = Employee.objects.filter(end_date__gt=datetime.now()).order_by('-start_date')
Or is there a more efficient way of doing the same?
Your second example looks fine. I corrected the filter parameters to match your start_date constraints. Also, i added a LIMIT 1 ([:1]) for better performance:
now = datetime.now()
employees = Employee.objects.filter(start_date__lt=now, end_date__gt=now).order_by('-start_date')
employee = employees[:1][0] if employees else None
In django, I want to get the age (in days) of an instance of a class. I tried doing that by subtracting its creation date field from today, but it does not seem to work properly. date.today() works fine, but DateField is giving me trouble. I looked at its source code and the django docs online for my version but I'm not sure how to manipulate it to perform the subtraction.
import datetime.date
from django.db import models
class MyItem(models.Model):
item_name = models.CharField(max_length = 30)
creation_date = models.DateField()
def age(self):
return date.today() - creation_date
my_first_item = MyItem(item_name = 'First', creation_date = '2005-11-01')
print my_first_item.age.days
Any input would be greatly appreciated!
Your problem is that you are trying to use a field instance outside of a model to represent a value.
models.DateField is a class which represents a database field with a type of "date". I suspect that you are looking to do one of the following:
Just do straight date math
Work with a value returned by a model
In the case of 1, you don't want to use Django's models at all. All you need and want is python's date and time handling classes. For your specific example all you need to use is a pair of date objects and you will end up with a timedelta object.
To do what you were trying to do in your example with the python standard classes, see the example below:
from datetime import date
birthday = date(year=2005, month=11, day=1)
today = date.today()
age = today - birthday
print age.days()
Here we instantiate a date with the birthdate values, we get a date with today's values, subtract them to get a timedelta, and finally print the number of days between the two dates.
In the case of 2, let's look at an example model:
class Person(models.Model):
name = models.CharField(max_length=100)
birthday = models.DateField()
Here we have a model where we've used models.CharField and models.DateField to describe a table in the database which contains a "varchar" column and a "date" column. When we fetch instances of this model using the ORM, Django handles converting whatever value the database returns to a native datatype. Now let's look at some code that figures out the age of an instance of a person:
from datetime import date
from myapp.models import Person
person = Person.objects.get(id=1)
age = date.today() - person.birthday
print age.days
Here you can see that we fetch an instance of the person model from the database and then we subtract their birthday from today. We're able to do this here, because when we access "person.birthday" Django is transforming whatever value the database returned into a python date object. This is the same type as the date object returned by "date.today()" so the "-" operator makes sense. The result of the subtraction operation is a timedelta object.