Skip to content

Instantly share code, notes, and snippets.

@duahimanshu100
Last active September 16, 2019 17:29
Show Gist options
  • Select an option

  • Save duahimanshu100/0bc9e08d2db4370fe492772ad33edecb to your computer and use it in GitHub Desktop.

Select an option

Save duahimanshu100/0bc9e08d2db4370fe492772ad33edecb to your computer and use it in GitHub Desktop.
from datetime import datetime
from django.contrib.auth.models import User
def update_user_first_name(user_id, new_first_name):
return User.objects.filter(id=user_id).update(first_name=new_first_name)
def get_user_groups(user_id):
try:
user = User.objects.prefetch_related('groups').get(id=user_id)
except User.DoesNotExist:
return
return list(user.groups.values_list('name', flat=True))
def parse_str_date_to_date_obj(str_date, format='%Y-%m-%d'):
try:
# we can use utc timezone or the timezone from the settings
return datetime.strptime(str_date, format).replace(tzinfo=timezone.utc)
except ValueError:
raise ValueError('Provided Date format is not correct')
def count_user_joined_btw(date1, date2):
date1 = parse_str_date_to_date_obj(date1)
date2 = parse_str_date_to_date_obj(date2)
if date1 > date2:
smaller_date = date2
greater_date = date1
else:
smaller_date = date1
greater_date = date2
return User.objects.filter(date_joined__lte=greater_date).filter(date_joined__gte=smaller_date).count()
@duahimanshu100
Copy link
Author

duahimanshu100 commented Sep 16, 2019

get_user_groups:
Are you sure? prefetch_related retrieves all related objects of a certain kind in one query. So all groups for all matches users. But still one query for the user and one query for the groups. Maybe try from the other side.

oops my bad, it was pretty simple
Group.objects.filter(user=user_id).values_list('name',flat=True)

@duahimanshu100
Copy link
Author

So our SQL would now be date_joined >= '2016-01-01 00:00:00' AND date_joined <= '2016-04-01 00:00:00'.
This would exclude all users joined on the 1st of April except for the very first second of the day. There is an easy ORM tool that will simplify your query a lot.

We can use __date
User.objects.filter(date_joined__date__lte=obj_datetime1.date()).filter(date_joined__date__gte=obj_datetime2.date()).

Query will be like django_datetime_cast_date("users_user"."date_joined", 'UTC') >= 2019-01-01 and django_datetime_cast_date("users_user"."date_joined", 'UTC') <= 2019-04-01

@duahimanshu100
Copy link
Author

count_user_joined_btw:
If you don't like it, why did you made the parameters arbitrary?

Because I don't know where this function is called from the application.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment