Django QuerySet annotation. How to make aware datetime with user's timezone from F expression?

911 Views Asked by At

I've created a Django 1.11. application. I have a model to store periods of time for users

WeeklySchedule(models.Model):

    """Model representing a weekly schedule of user"""

    user_profile = models.ForeignKey(UserProfile)

    DAY_OF_WEEK =(
    (1,'Monday'),
    (2, 'Tuesday'),
    (3, 'Wednesday'),
    (4, 'Thursday'),
    (5, 'Friday'),
    (6, 'Saturday'),
    (7, 'Sunday'),
    )
    day_of_week = models.IntegerField(choices=DAY_OF_WEEK)

    time_from = models.TimeField()
    time_to = models.TimeField()

and I have a model for user's profile

class UserProfile(models.Model):

    # This line is required. Links UserProfile to a User model instance.
    user = models.OneToOneField(User, related_name='profile')

    # The additional attributes we wish to include.

    timezone = models.CharField(
        max_length=255,
        choices=[(t,t) for t in pytz.common_timezones],
        blank=True, null=True)

First of all, I try to get aware datetime according user's timezone and to convert all date times in utc later, but I've got an error using make_aware method with F expression:

from django.utils import timezone

WeeklySchedule.objects.annotate(dt_from_aware=timezone.make_aware(datetime.date.today() + F('time_from'))).values()


Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/django/utils/timezone.py",     line 285, in make_aware
return timezone.localize(value, is_dst=is_dst)
File "/usr/local/lib/python3.6/site-packages/pytz/__init__.py", line 226, in localize
if dt.tzinfo is not None:
AttributeError: 'CombinedExpression' object has no attribute 'tzinfo'
0

There are 0 best solutions below