Django QuerySet date manipulation










0















I have a model storing, among other things, a timezone datetime object. I am reaching out with an Ajax call from the website to one of my views, which does the following call:



def uploads(request):

user = User.objects.get(username=request.user.get_username())
cases = Case.objects.filter(user_id=user.pk).order_by('-uploaded_on')[:5]

return JsonResponse(serializers.serialize('json', cases, fields=('col1', 'col2', 'col3', 'uploaded_on')), safe=False)


When a JSON response is received at the Front End, it gets parsed with JS and analyzed. What I would like to do here, is to modify the 'uploaded_on' column with user's timezone (which I can already access with user.timezone, currently displayed as a string e.g. 'Germany/Berlin', but can easily convert it to a necessary object with e.g. pytz package).



When I try to iterate through the QuerySet like below, the values received on the Front End do not change:



for case in cases:
case.uploaded_on.astimezone(pytz.timezone(user.timezone))


This is probably related to the fact that QuerySets are lazy, like described in Django's documentation. Can anyone suggest how this can be done?



A bonus question as well: with Django's serializer, can I pass along more than one QuerySet in a single JSON response? When I try to pack a few in a list, I get a MultiValueDictKeyError:



return JsonResponse(serializers.serialize('json', [cases, cases2]), safe=False)









share|improve this question


























    0















    I have a model storing, among other things, a timezone datetime object. I am reaching out with an Ajax call from the website to one of my views, which does the following call:



    def uploads(request):

    user = User.objects.get(username=request.user.get_username())
    cases = Case.objects.filter(user_id=user.pk).order_by('-uploaded_on')[:5]

    return JsonResponse(serializers.serialize('json', cases, fields=('col1', 'col2', 'col3', 'uploaded_on')), safe=False)


    When a JSON response is received at the Front End, it gets parsed with JS and analyzed. What I would like to do here, is to modify the 'uploaded_on' column with user's timezone (which I can already access with user.timezone, currently displayed as a string e.g. 'Germany/Berlin', but can easily convert it to a necessary object with e.g. pytz package).



    When I try to iterate through the QuerySet like below, the values received on the Front End do not change:



    for case in cases:
    case.uploaded_on.astimezone(pytz.timezone(user.timezone))


    This is probably related to the fact that QuerySets are lazy, like described in Django's documentation. Can anyone suggest how this can be done?



    A bonus question as well: with Django's serializer, can I pass along more than one QuerySet in a single JSON response? When I try to pack a few in a list, I get a MultiValueDictKeyError:



    return JsonResponse(serializers.serialize('json', [cases, cases2]), safe=False)









    share|improve this question
























      0












      0








      0








      I have a model storing, among other things, a timezone datetime object. I am reaching out with an Ajax call from the website to one of my views, which does the following call:



      def uploads(request):

      user = User.objects.get(username=request.user.get_username())
      cases = Case.objects.filter(user_id=user.pk).order_by('-uploaded_on')[:5]

      return JsonResponse(serializers.serialize('json', cases, fields=('col1', 'col2', 'col3', 'uploaded_on')), safe=False)


      When a JSON response is received at the Front End, it gets parsed with JS and analyzed. What I would like to do here, is to modify the 'uploaded_on' column with user's timezone (which I can already access with user.timezone, currently displayed as a string e.g. 'Germany/Berlin', but can easily convert it to a necessary object with e.g. pytz package).



      When I try to iterate through the QuerySet like below, the values received on the Front End do not change:



      for case in cases:
      case.uploaded_on.astimezone(pytz.timezone(user.timezone))


      This is probably related to the fact that QuerySets are lazy, like described in Django's documentation. Can anyone suggest how this can be done?



      A bonus question as well: with Django's serializer, can I pass along more than one QuerySet in a single JSON response? When I try to pack a few in a list, I get a MultiValueDictKeyError:



      return JsonResponse(serializers.serialize('json', [cases, cases2]), safe=False)









      share|improve this question














      I have a model storing, among other things, a timezone datetime object. I am reaching out with an Ajax call from the website to one of my views, which does the following call:



      def uploads(request):

      user = User.objects.get(username=request.user.get_username())
      cases = Case.objects.filter(user_id=user.pk).order_by('-uploaded_on')[:5]

      return JsonResponse(serializers.serialize('json', cases, fields=('col1', 'col2', 'col3', 'uploaded_on')), safe=False)


      When a JSON response is received at the Front End, it gets parsed with JS and analyzed. What I would like to do here, is to modify the 'uploaded_on' column with user's timezone (which I can already access with user.timezone, currently displayed as a string e.g. 'Germany/Berlin', but can easily convert it to a necessary object with e.g. pytz package).



      When I try to iterate through the QuerySet like below, the values received on the Front End do not change:



      for case in cases:
      case.uploaded_on.astimezone(pytz.timezone(user.timezone))


      This is probably related to the fact that QuerySets are lazy, like described in Django's documentation. Can anyone suggest how this can be done?



      A bonus question as well: with Django's serializer, can I pass along more than one QuerySet in a single JSON response? When I try to pack a few in a list, I get a MultiValueDictKeyError:



      return JsonResponse(serializers.serialize('json', [cases, cases2]), safe=False)






      python json django timezone






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 23:14









      Greem666Greem666

      9810




      9810






















          2 Answers
          2






          active

          oldest

          votes


















          0














          To me there would be two approaches:




          1. Annotate the cases queryset with a new column, something like uploaded_at_utz and do timezone manipulation at database level. For example you could use TruncSecond function to do something like the following:



            cases = Case.objects.filter(user_id=user.pk).annotate(uploaded_at_utz=TruncSecond('uploaded_on', tzinfo=pytz.timezone(user.timezone)).order_by('-uploaded_on')[:5]



          2. The other approach would be to do this at python level. For this I would go for a generator function, something like:



            def convert_to_timezone(cases, tzinfo):
            for case in cases:
            case.uploaded_on = case.uploaded_on.astimezone(tzinfo)
            yield case


          Then, in you would pass convert_to_timezone(cases, pytz.timezone(user.timezone)) to your JsonResponse constructor.



          You should also explore the use of timezone.override and/or timezone.localtime although I'm not familiar with them.






          share|improve this answer






























            0














            Regarding the date manipulation, datetime.astimezone() returns a new datetime rather than converting in-place. You'd need to assign the converted value back to case.uploaded_on.



            for case in cases:
            case.uploaded_on = case.uploaded_on.astimezone(pytz.timezone(user.timezone))


            Regarding whether you can pass along more than one queryset in a single JSON response, you can use itertools.chain to do that.



            from itertools import chain

            return JsonResponse(serializers.serialize('json', chain(cases, cases2)), safe=False)





            share|improve this answer






















              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53290901%2fdjango-queryset-date-manipulation%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              To me there would be two approaches:




              1. Annotate the cases queryset with a new column, something like uploaded_at_utz and do timezone manipulation at database level. For example you could use TruncSecond function to do something like the following:



                cases = Case.objects.filter(user_id=user.pk).annotate(uploaded_at_utz=TruncSecond('uploaded_on', tzinfo=pytz.timezone(user.timezone)).order_by('-uploaded_on')[:5]



              2. The other approach would be to do this at python level. For this I would go for a generator function, something like:



                def convert_to_timezone(cases, tzinfo):
                for case in cases:
                case.uploaded_on = case.uploaded_on.astimezone(tzinfo)
                yield case


              Then, in you would pass convert_to_timezone(cases, pytz.timezone(user.timezone)) to your JsonResponse constructor.



              You should also explore the use of timezone.override and/or timezone.localtime although I'm not familiar with them.






              share|improve this answer



























                0














                To me there would be two approaches:




                1. Annotate the cases queryset with a new column, something like uploaded_at_utz and do timezone manipulation at database level. For example you could use TruncSecond function to do something like the following:



                  cases = Case.objects.filter(user_id=user.pk).annotate(uploaded_at_utz=TruncSecond('uploaded_on', tzinfo=pytz.timezone(user.timezone)).order_by('-uploaded_on')[:5]



                2. The other approach would be to do this at python level. For this I would go for a generator function, something like:



                  def convert_to_timezone(cases, tzinfo):
                  for case in cases:
                  case.uploaded_on = case.uploaded_on.astimezone(tzinfo)
                  yield case


                Then, in you would pass convert_to_timezone(cases, pytz.timezone(user.timezone)) to your JsonResponse constructor.



                You should also explore the use of timezone.override and/or timezone.localtime although I'm not familiar with them.






                share|improve this answer

























                  0












                  0








                  0







                  To me there would be two approaches:




                  1. Annotate the cases queryset with a new column, something like uploaded_at_utz and do timezone manipulation at database level. For example you could use TruncSecond function to do something like the following:



                    cases = Case.objects.filter(user_id=user.pk).annotate(uploaded_at_utz=TruncSecond('uploaded_on', tzinfo=pytz.timezone(user.timezone)).order_by('-uploaded_on')[:5]



                  2. The other approach would be to do this at python level. For this I would go for a generator function, something like:



                    def convert_to_timezone(cases, tzinfo):
                    for case in cases:
                    case.uploaded_on = case.uploaded_on.astimezone(tzinfo)
                    yield case


                  Then, in you would pass convert_to_timezone(cases, pytz.timezone(user.timezone)) to your JsonResponse constructor.



                  You should also explore the use of timezone.override and/or timezone.localtime although I'm not familiar with them.






                  share|improve this answer













                  To me there would be two approaches:




                  1. Annotate the cases queryset with a new column, something like uploaded_at_utz and do timezone manipulation at database level. For example you could use TruncSecond function to do something like the following:



                    cases = Case.objects.filter(user_id=user.pk).annotate(uploaded_at_utz=TruncSecond('uploaded_on', tzinfo=pytz.timezone(user.timezone)).order_by('-uploaded_on')[:5]



                  2. The other approach would be to do this at python level. For this I would go for a generator function, something like:



                    def convert_to_timezone(cases, tzinfo):
                    for case in cases:
                    case.uploaded_on = case.uploaded_on.astimezone(tzinfo)
                    yield case


                  Then, in you would pass convert_to_timezone(cases, pytz.timezone(user.timezone)) to your JsonResponse constructor.



                  You should also explore the use of timezone.override and/or timezone.localtime although I'm not familiar with them.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 14 '18 at 0:24









                  ivissaniivissani

                  58147




                  58147























                      0














                      Regarding the date manipulation, datetime.astimezone() returns a new datetime rather than converting in-place. You'd need to assign the converted value back to case.uploaded_on.



                      for case in cases:
                      case.uploaded_on = case.uploaded_on.astimezone(pytz.timezone(user.timezone))


                      Regarding whether you can pass along more than one queryset in a single JSON response, you can use itertools.chain to do that.



                      from itertools import chain

                      return JsonResponse(serializers.serialize('json', chain(cases, cases2)), safe=False)





                      share|improve this answer



























                        0














                        Regarding the date manipulation, datetime.astimezone() returns a new datetime rather than converting in-place. You'd need to assign the converted value back to case.uploaded_on.



                        for case in cases:
                        case.uploaded_on = case.uploaded_on.astimezone(pytz.timezone(user.timezone))


                        Regarding whether you can pass along more than one queryset in a single JSON response, you can use itertools.chain to do that.



                        from itertools import chain

                        return JsonResponse(serializers.serialize('json', chain(cases, cases2)), safe=False)





                        share|improve this answer

























                          0












                          0








                          0







                          Regarding the date manipulation, datetime.astimezone() returns a new datetime rather than converting in-place. You'd need to assign the converted value back to case.uploaded_on.



                          for case in cases:
                          case.uploaded_on = case.uploaded_on.astimezone(pytz.timezone(user.timezone))


                          Regarding whether you can pass along more than one queryset in a single JSON response, you can use itertools.chain to do that.



                          from itertools import chain

                          return JsonResponse(serializers.serialize('json', chain(cases, cases2)), safe=False)





                          share|improve this answer













                          Regarding the date manipulation, datetime.astimezone() returns a new datetime rather than converting in-place. You'd need to assign the converted value back to case.uploaded_on.



                          for case in cases:
                          case.uploaded_on = case.uploaded_on.astimezone(pytz.timezone(user.timezone))


                          Regarding whether you can pass along more than one queryset in a single JSON response, you can use itertools.chain to do that.



                          from itertools import chain

                          return JsonResponse(serializers.serialize('json', chain(cases, cases2)), safe=False)






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 14 '18 at 13:25









                          Will KeelingWill Keeling

                          11.7k22434




                          11.7k22434



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53290901%2fdjango-queryset-date-manipulation%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              這個網誌中的熱門文章

                              How to read a connectionString WITH PROVIDER in .NET Core?

                              Node.js Script on GitHub Pages or Amazon S3

                              Museum of Modern and Contemporary Art of Trento and Rovereto