Django: ordering a queryset by dictionary added valuesHow to combine 2 or more querysets in a Django view?How do I do a not equal in Django queryset filtering?Does Django scale?django - inlineformset_factory with more than one ForeignKeyDjango south migration error with unique field in postgresql databaseUpdate object attribute with one click in djangoDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?Using Tag model to create ManytoMany relationshipHow to set dynamic initial values to django modelform field

Why are there five extra turns in tournament Magic?

Would a "ring language" be possible?

Managing heat dissipation in a magic wand

FIFO data structure in pure C

Parse a C++14 integer literal

Gambler's Fallacy Dice

Why does the U.S military use mercenaries?

How do I balance a campaign consisting of four kobold PCs?

Why is Drogon so much better in battle than Rhaegal and Viserion?

Is my homebrew Awakened Bear race balanced?

Shortest amud or daf in Shas?

Divisor Rich and Poor Numbers

Cathy’s Composite party is powered by three Prime Pals. Can you find them?

on the truth quest vs in the quest for truth

Does the US Supreme Court vote using secret ballots?

Is it a good idea to teach algorithm courses using pseudocode?

Why are stats in Angband written as 18/** instead of 19, 20...?

Will this series of events work to drown the Tarrasque?

How would fantasy dwarves exist, realistically?

What were the "pills" that were added to solid waste in Apollo 7?

Is my company merging branches wrong?

Why aren't satellites disintegrated even though they orbit earth within earth's Roche Limits?

Who is frowning in the sentence "Daisy looked at Tom frowning"?

Can the Gate spell draw a creature larger that 20 feet in every dimension through the portal it creates?



Django: ordering a queryset by dictionary added values


How to combine 2 or more querysets in a Django view?How do I do a not equal in Django queryset filtering?Does Django scale?django - inlineformset_factory with more than one ForeignKeyDjango south migration error with unique field in postgresql databaseUpdate object attribute with one click in djangoDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?Using Tag model to create ManytoMany relationshipHow to set dynamic initial values to django modelform field






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm trying to sort a queryset of dictionaries to which I added some calculated values.



The process:



class Inventario(models.Model):
codigo_kinemed = models.CharField(max_length=100)
existencias = models.IntegerField(help_text="Existencias ", blank=True, null=True)
valor_coste = models.IntegerField(help_text="Existencias ", blank=True, null=True)
valor_venta = models.IntegerField(help_text="Existencias ", blank=True, null=True)
fecha = models.DateField(help_text="Fecha de toma de datos", blank=True, null=True)

def __str__(self):
return str(self.codigo_kinemed)


I get a queryset from that.



inventario_diferencia = Inventario.objects.filter(fecha=ultima_fecha_cargada.fecha).values()


That returns a queryset of dictionaries. Then I iterate over that queryset and calculate some new fields.



for este in inventario_diferencia:
este['stock_valor_venta'] = este['existencias'] * este['valor_venta']


I can print that calculated field with no problem in the template.



 inventario_diferencia.stock_valor_venta 


Ordering



I want to sort that queryset by the new stock_valor_ventavalue I added.



When I try the usual queryset



inventario_diferencia.order_by('stock_valor_venta')


I get:




Cannot resolve keyword 'diferencia_mes' into field. Choices are: codigo_kinemed, existencias, fecha, id, valor_coste, valor_venta




Those are the model´s original values, so no option to order by the new value. When I try to sort it like a dictionary



inventario_diferencia = sorted(inventario_diferencia, key=lambda t: t.diferencia_mes)


I get




'dict' object has no attribute 'diferencia_mes'




Documentation



In the Django doc https://docs.djangoproject.com/en/2.1/ref/models/querysets/#values states the following:



values(*fields, **expressions) Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.


Is my problem related to the "when used as an iterable" part of the statement? How can I sort that kind of querysets by added values?



Thanks in advance!










share|improve this question






























    0















    I'm trying to sort a queryset of dictionaries to which I added some calculated values.



    The process:



    class Inventario(models.Model):
    codigo_kinemed = models.CharField(max_length=100)
    existencias = models.IntegerField(help_text="Existencias ", blank=True, null=True)
    valor_coste = models.IntegerField(help_text="Existencias ", blank=True, null=True)
    valor_venta = models.IntegerField(help_text="Existencias ", blank=True, null=True)
    fecha = models.DateField(help_text="Fecha de toma de datos", blank=True, null=True)

    def __str__(self):
    return str(self.codigo_kinemed)


    I get a queryset from that.



    inventario_diferencia = Inventario.objects.filter(fecha=ultima_fecha_cargada.fecha).values()


    That returns a queryset of dictionaries. Then I iterate over that queryset and calculate some new fields.



    for este in inventario_diferencia:
    este['stock_valor_venta'] = este['existencias'] * este['valor_venta']


    I can print that calculated field with no problem in the template.



     inventario_diferencia.stock_valor_venta 


    Ordering



    I want to sort that queryset by the new stock_valor_ventavalue I added.



    When I try the usual queryset



    inventario_diferencia.order_by('stock_valor_venta')


    I get:




    Cannot resolve keyword 'diferencia_mes' into field. Choices are: codigo_kinemed, existencias, fecha, id, valor_coste, valor_venta




    Those are the model´s original values, so no option to order by the new value. When I try to sort it like a dictionary



    inventario_diferencia = sorted(inventario_diferencia, key=lambda t: t.diferencia_mes)


    I get




    'dict' object has no attribute 'diferencia_mes'




    Documentation



    In the Django doc https://docs.djangoproject.com/en/2.1/ref/models/querysets/#values states the following:



    values(*fields, **expressions) Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.


    Is my problem related to the "when used as an iterable" part of the statement? How can I sort that kind of querysets by added values?



    Thanks in advance!










    share|improve this question


























      0












      0








      0








      I'm trying to sort a queryset of dictionaries to which I added some calculated values.



      The process:



      class Inventario(models.Model):
      codigo_kinemed = models.CharField(max_length=100)
      existencias = models.IntegerField(help_text="Existencias ", blank=True, null=True)
      valor_coste = models.IntegerField(help_text="Existencias ", blank=True, null=True)
      valor_venta = models.IntegerField(help_text="Existencias ", blank=True, null=True)
      fecha = models.DateField(help_text="Fecha de toma de datos", blank=True, null=True)

      def __str__(self):
      return str(self.codigo_kinemed)


      I get a queryset from that.



      inventario_diferencia = Inventario.objects.filter(fecha=ultima_fecha_cargada.fecha).values()


      That returns a queryset of dictionaries. Then I iterate over that queryset and calculate some new fields.



      for este in inventario_diferencia:
      este['stock_valor_venta'] = este['existencias'] * este['valor_venta']


      I can print that calculated field with no problem in the template.



       inventario_diferencia.stock_valor_venta 


      Ordering



      I want to sort that queryset by the new stock_valor_ventavalue I added.



      When I try the usual queryset



      inventario_diferencia.order_by('stock_valor_venta')


      I get:




      Cannot resolve keyword 'diferencia_mes' into field. Choices are: codigo_kinemed, existencias, fecha, id, valor_coste, valor_venta




      Those are the model´s original values, so no option to order by the new value. When I try to sort it like a dictionary



      inventario_diferencia = sorted(inventario_diferencia, key=lambda t: t.diferencia_mes)


      I get




      'dict' object has no attribute 'diferencia_mes'




      Documentation



      In the Django doc https://docs.djangoproject.com/en/2.1/ref/models/querysets/#values states the following:



      values(*fields, **expressions) Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.


      Is my problem related to the "when used as an iterable" part of the statement? How can I sort that kind of querysets by added values?



      Thanks in advance!










      share|improve this question
















      I'm trying to sort a queryset of dictionaries to which I added some calculated values.



      The process:



      class Inventario(models.Model):
      codigo_kinemed = models.CharField(max_length=100)
      existencias = models.IntegerField(help_text="Existencias ", blank=True, null=True)
      valor_coste = models.IntegerField(help_text="Existencias ", blank=True, null=True)
      valor_venta = models.IntegerField(help_text="Existencias ", blank=True, null=True)
      fecha = models.DateField(help_text="Fecha de toma de datos", blank=True, null=True)

      def __str__(self):
      return str(self.codigo_kinemed)


      I get a queryset from that.



      inventario_diferencia = Inventario.objects.filter(fecha=ultima_fecha_cargada.fecha).values()


      That returns a queryset of dictionaries. Then I iterate over that queryset and calculate some new fields.



      for este in inventario_diferencia:
      este['stock_valor_venta'] = este['existencias'] * este['valor_venta']


      I can print that calculated field with no problem in the template.



       inventario_diferencia.stock_valor_venta 


      Ordering



      I want to sort that queryset by the new stock_valor_ventavalue I added.



      When I try the usual queryset



      inventario_diferencia.order_by('stock_valor_venta')


      I get:




      Cannot resolve keyword 'diferencia_mes' into field. Choices are: codigo_kinemed, existencias, fecha, id, valor_coste, valor_venta




      Those are the model´s original values, so no option to order by the new value. When I try to sort it like a dictionary



      inventario_diferencia = sorted(inventario_diferencia, key=lambda t: t.diferencia_mes)


      I get




      'dict' object has no attribute 'diferencia_mes'




      Documentation



      In the Django doc https://docs.djangoproject.com/en/2.1/ref/models/querysets/#values states the following:



      values(*fields, **expressions) Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.


      Is my problem related to the "when used as an iterable" part of the statement? How can I sort that kind of querysets by added values?



      Thanks in advance!







      django django-queryset






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 29 at 21:47









      marc_s

      589k13111291277




      589k13111291277










      asked Mar 23 at 17:38









      Francisco GhelfiFrancisco Ghelfi

      74115




      74115






















          1 Answer
          1






          active

          oldest

          votes


















          3














          You should look into using annotate. You could create the a field that is equal to the product of your two fields then order by that in SQL.



          from django.db.models import F
          inventario_diferencia = Inventario.objects.filter(
          fecha=ultima_fecha_cargada.fecha
          ).annotate(
          stock_valor_venta=F('existencias') * F('valor_venta')
          ).order_by('-stock_valor_venta')

          print(inventorio_deiferencia.first().stock_valor_venta)





          share|improve this answer























          • What if I have an annotation relating a calculation from other query? Something like: venta_historica=ventas.filter(prod_codigo=F('codigo_kinemed')).aggregate(Sum("uds")).get("uds__sum")

            – Francisco Ghelfi
            Mar 23 at 20:54











          • I don't understand what you're asking.

            – schillingt
            Mar 23 at 21:10











          • I´ll start another question

            – Francisco Ghelfi
            Mar 23 at 21:58











          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%2f55316563%2fdjango-ordering-a-queryset-by-dictionary-added-values%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          You should look into using annotate. You could create the a field that is equal to the product of your two fields then order by that in SQL.



          from django.db.models import F
          inventario_diferencia = Inventario.objects.filter(
          fecha=ultima_fecha_cargada.fecha
          ).annotate(
          stock_valor_venta=F('existencias') * F('valor_venta')
          ).order_by('-stock_valor_venta')

          print(inventorio_deiferencia.first().stock_valor_venta)





          share|improve this answer























          • What if I have an annotation relating a calculation from other query? Something like: venta_historica=ventas.filter(prod_codigo=F('codigo_kinemed')).aggregate(Sum("uds")).get("uds__sum")

            – Francisco Ghelfi
            Mar 23 at 20:54











          • I don't understand what you're asking.

            – schillingt
            Mar 23 at 21:10











          • I´ll start another question

            – Francisco Ghelfi
            Mar 23 at 21:58















          3














          You should look into using annotate. You could create the a field that is equal to the product of your two fields then order by that in SQL.



          from django.db.models import F
          inventario_diferencia = Inventario.objects.filter(
          fecha=ultima_fecha_cargada.fecha
          ).annotate(
          stock_valor_venta=F('existencias') * F('valor_venta')
          ).order_by('-stock_valor_venta')

          print(inventorio_deiferencia.first().stock_valor_venta)





          share|improve this answer























          • What if I have an annotation relating a calculation from other query? Something like: venta_historica=ventas.filter(prod_codigo=F('codigo_kinemed')).aggregate(Sum("uds")).get("uds__sum")

            – Francisco Ghelfi
            Mar 23 at 20:54











          • I don't understand what you're asking.

            – schillingt
            Mar 23 at 21:10











          • I´ll start another question

            – Francisco Ghelfi
            Mar 23 at 21:58













          3












          3








          3







          You should look into using annotate. You could create the a field that is equal to the product of your two fields then order by that in SQL.



          from django.db.models import F
          inventario_diferencia = Inventario.objects.filter(
          fecha=ultima_fecha_cargada.fecha
          ).annotate(
          stock_valor_venta=F('existencias') * F('valor_venta')
          ).order_by('-stock_valor_venta')

          print(inventorio_deiferencia.first().stock_valor_venta)





          share|improve this answer













          You should look into using annotate. You could create the a field that is equal to the product of your two fields then order by that in SQL.



          from django.db.models import F
          inventario_diferencia = Inventario.objects.filter(
          fecha=ultima_fecha_cargada.fecha
          ).annotate(
          stock_valor_venta=F('existencias') * F('valor_venta')
          ).order_by('-stock_valor_venta')

          print(inventorio_deiferencia.first().stock_valor_venta)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 23 at 18:08









          schillingtschillingt

          6,40511824




          6,40511824












          • What if I have an annotation relating a calculation from other query? Something like: venta_historica=ventas.filter(prod_codigo=F('codigo_kinemed')).aggregate(Sum("uds")).get("uds__sum")

            – Francisco Ghelfi
            Mar 23 at 20:54











          • I don't understand what you're asking.

            – schillingt
            Mar 23 at 21:10











          • I´ll start another question

            – Francisco Ghelfi
            Mar 23 at 21:58

















          • What if I have an annotation relating a calculation from other query? Something like: venta_historica=ventas.filter(prod_codigo=F('codigo_kinemed')).aggregate(Sum("uds")).get("uds__sum")

            – Francisco Ghelfi
            Mar 23 at 20:54











          • I don't understand what you're asking.

            – schillingt
            Mar 23 at 21:10











          • I´ll start another question

            – Francisco Ghelfi
            Mar 23 at 21:58
















          What if I have an annotation relating a calculation from other query? Something like: venta_historica=ventas.filter(prod_codigo=F('codigo_kinemed')).aggregate(Sum("uds")).get("uds__sum")

          – Francisco Ghelfi
          Mar 23 at 20:54





          What if I have an annotation relating a calculation from other query? Something like: venta_historica=ventas.filter(prod_codigo=F('codigo_kinemed')).aggregate(Sum("uds")).get("uds__sum")

          – Francisco Ghelfi
          Mar 23 at 20:54













          I don't understand what you're asking.

          – schillingt
          Mar 23 at 21:10





          I don't understand what you're asking.

          – schillingt
          Mar 23 at 21:10













          I´ll start another question

          – Francisco Ghelfi
          Mar 23 at 21:58





          I´ll start another question

          – Francisco Ghelfi
          Mar 23 at 21:58



















          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%2f55316563%2fdjango-ordering-a-queryset-by-dictionary-added-values%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







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현