-
-
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() |
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)
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
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.
Signals are also not called when you use update