Issues with queryset and slicingHow to combine 2 or more querysets in a Django view?How do I do a not equal in Django queryset filtering?Filtering for empty or NULL names in a querysetGetting the SQL from a Django QuerySetFilter with two models in one queryset - Advanced search djangodjango - filter after slice / filter on queryset where results have been limitedRedirect and 'field' keyword issues when retriving objects from databaseThe QuerySet value for an exact lookup must be limited to one result using slicing-DjangoDjango - how can I do this query in the ORMHow to remove Django redundant inner join

How to get directions in deep space?

What fields between the rationals and the reals allow a good notion of 2D distance?

"before" and "want" for the same systemd service?

How much of a Devil Fruit must be consumed to gain the power?

Do we have to expect a queue for the shuttle from Watford Junction to Harry Potter Studio?

What is going on with gets(stdin) on the site coderbyte?

What are some good ways to treat frozen vegetables such that they behave like fresh vegetables when stir frying them?

US tourist/student visa

I found an audio circuit and I built it just fine, but I find it a bit too quiet. How do I amplify the output so that it is a bit louder?

Shouldn’t conservatives embrace universal basic income?

Does grappling negate Mirror Image?

Review your own paper in Mathematics

What is the difference between lands and mana?

Is it allowed to activate the ability of multiple planeswalkers in a single turn?

A Trivial Diagnosis

Can I turn my anal-retentiveness into a career?

Does "he squandered his car on drink" sound natural?

Make a Bowl of Alphabet Soup

How do I tell my boss that I'm quitting soon, especially given that a colleague just left this week

A variation to the phrase "hanging over my shoulders"

Does the reader need to like the PoV character?

C++ copy constructor called at return

Why is the Sun approximated as a black body at ~ 5800 K?

What is Cash Advance APR?



Issues with queryset and slicing


How to combine 2 or more querysets in a Django view?How do I do a not equal in Django queryset filtering?Filtering for empty or NULL names in a querysetGetting the SQL from a Django QuerySetFilter with two models in one queryset - Advanced search djangodjango - filter after slice / filter on queryset where results have been limitedRedirect and 'field' keyword issues when retriving objects from databaseThe QuerySet value for an exact lookup must be limited to one result using slicing-DjangoDjango - how can I do this query in the ORMHow to remove Django redundant inner join













9















I have 2 models, Company and Product, with Product having a ForeignKey to Company



class Product(Meta):
company = models.ForeignKey(
Company,
related_name='products',
on_delete=models.CASCADE
)


I do the following filtering:



 company = Company.objects.filter(account=account, pk=company_pk)
if not company:
raise Http404
product = Product.objects.filter(company=company, pk=product_pk)
if not product:
raise Http404
return product


And I have the following error:



The QuerySet value for an exact lookup must be limited to one result using slicing.


company_pk and product_pk are just variables. If I remove the Product filter there is no error.



I presume it happens because company result is a QuerySet and is pushed as argument in Product.objects.filter










share|improve this question




























    9















    I have 2 models, Company and Product, with Product having a ForeignKey to Company



    class Product(Meta):
    company = models.ForeignKey(
    Company,
    related_name='products',
    on_delete=models.CASCADE
    )


    I do the following filtering:



     company = Company.objects.filter(account=account, pk=company_pk)
    if not company:
    raise Http404
    product = Product.objects.filter(company=company, pk=product_pk)
    if not product:
    raise Http404
    return product


    And I have the following error:



    The QuerySet value for an exact lookup must be limited to one result using slicing.


    company_pk and product_pk are just variables. If I remove the Product filter there is no error.



    I presume it happens because company result is a QuerySet and is pushed as argument in Product.objects.filter










    share|improve this question


























      9












      9








      9


      0






      I have 2 models, Company and Product, with Product having a ForeignKey to Company



      class Product(Meta):
      company = models.ForeignKey(
      Company,
      related_name='products',
      on_delete=models.CASCADE
      )


      I do the following filtering:



       company = Company.objects.filter(account=account, pk=company_pk)
      if not company:
      raise Http404
      product = Product.objects.filter(company=company, pk=product_pk)
      if not product:
      raise Http404
      return product


      And I have the following error:



      The QuerySet value for an exact lookup must be limited to one result using slicing.


      company_pk and product_pk are just variables. If I remove the Product filter there is no error.



      I presume it happens because company result is a QuerySet and is pushed as argument in Product.objects.filter










      share|improve this question
















      I have 2 models, Company and Product, with Product having a ForeignKey to Company



      class Product(Meta):
      company = models.ForeignKey(
      Company,
      related_name='products',
      on_delete=models.CASCADE
      )


      I do the following filtering:



       company = Company.objects.filter(account=account, pk=company_pk)
      if not company:
      raise Http404
      product = Product.objects.filter(company=company, pk=product_pk)
      if not product:
      raise Http404
      return product


      And I have the following error:



      The QuerySet value for an exact lookup must be limited to one result using slicing.


      company_pk and product_pk are just variables. If I remove the Product filter there is no error.



      I presume it happens because company result is a QuerySet and is pushed as argument in Product.objects.filter







      django django-queryset






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 20 '18 at 8:20









      Serge Kishiko

      1519




      1519










      asked Dec 7 '17 at 18:39









      user3541631user3541631

      1,18321737




      1,18321737






















          3 Answers
          3






          active

          oldest

          votes


















          9














          Company is a queryset. You might want to do



          Product.objects.filter(company=company[0], pk=product_pk)


          Or better yet you can use the relations in the ORM to simplify into 1 lookup.



          Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk) 





          share|improve this answer























          • thanks, I didn't use [0] because I thought is just one result, but I presume is a list with one element

            – user3541631
            Dec 7 '17 at 18:47











          • filter returns a queryset, which is sliceable like a sequence. get is fine if you're sure that the pk exists, if it doesn't it'll throw an exception which you can catch and turn into a 404. Or if you're in a view, as it appears you are, you can use the get_object_or_404 shortcut: docs.djangoproject.com/en/1.11/topics/http/shortcuts/…

            – Peter DeGlopper
            Dec 7 '17 at 18:59











          • @kevswanberg - This Q&A was very difficult to find via a search. Would you consider expanding your answer to a generic example (such as: qs = Model1.objects.filter( attribute__in=Model2.objects.filter(##)) converted into your correct answer). As @TyrannoTaiwo and you both note, the error is thrown due to using a queryset within a queryset. But the error suggests slice as a problem - and searching around slices yields a lot of slicing a queryset type Q&A (making this specific use case issue difficult to find).

            – Bill Armstrong
            Jun 15 '18 at 5:02


















          9














          As said in the accepted answer, company is a queryset.



          The QuerySet value for an exact lookup must be limited to one result using slicing.


          Instead of this



          product = Product.objects.filter(company=company, pk=product_pk)


          try this



          product = Product.objects.filter(company__in=company, pk=product_pk)


          __in can handle querysets larger than one (multiple records of a table).



          This can be found in the django Many-to_one relationships section of the documentation.
          https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_one/



          Django documentation can be scary for a beginner like me because of its length and depth, though it provides solutions to most issues if you can crack it.






          share|improve this answer






























            0














            This error can also be created when you pass a queryset for the value you are searching with.



            Company.objects.filter(account=account, pk=company_pk) actually returns a queryset and that queryset can't be used in this query Product.objects.filter(company=company, pk=product_pk) without producing the error message.



            What is really missing here is a .get, either like



            company = Company.objects.filter(account=account, pk=company_pk).get()
            or company = Company.objects.get(account=account, pk=company_pk)






            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%2f47701679%2fissues-with-queryset-and-slicing%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              9














              Company is a queryset. You might want to do



              Product.objects.filter(company=company[0], pk=product_pk)


              Or better yet you can use the relations in the ORM to simplify into 1 lookup.



              Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk) 





              share|improve this answer























              • thanks, I didn't use [0] because I thought is just one result, but I presume is a list with one element

                – user3541631
                Dec 7 '17 at 18:47











              • filter returns a queryset, which is sliceable like a sequence. get is fine if you're sure that the pk exists, if it doesn't it'll throw an exception which you can catch and turn into a 404. Or if you're in a view, as it appears you are, you can use the get_object_or_404 shortcut: docs.djangoproject.com/en/1.11/topics/http/shortcuts/…

                – Peter DeGlopper
                Dec 7 '17 at 18:59











              • @kevswanberg - This Q&A was very difficult to find via a search. Would you consider expanding your answer to a generic example (such as: qs = Model1.objects.filter( attribute__in=Model2.objects.filter(##)) converted into your correct answer). As @TyrannoTaiwo and you both note, the error is thrown due to using a queryset within a queryset. But the error suggests slice as a problem - and searching around slices yields a lot of slicing a queryset type Q&A (making this specific use case issue difficult to find).

                – Bill Armstrong
                Jun 15 '18 at 5:02















              9














              Company is a queryset. You might want to do



              Product.objects.filter(company=company[0], pk=product_pk)


              Or better yet you can use the relations in the ORM to simplify into 1 lookup.



              Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk) 





              share|improve this answer























              • thanks, I didn't use [0] because I thought is just one result, but I presume is a list with one element

                – user3541631
                Dec 7 '17 at 18:47











              • filter returns a queryset, which is sliceable like a sequence. get is fine if you're sure that the pk exists, if it doesn't it'll throw an exception which you can catch and turn into a 404. Or if you're in a view, as it appears you are, you can use the get_object_or_404 shortcut: docs.djangoproject.com/en/1.11/topics/http/shortcuts/…

                – Peter DeGlopper
                Dec 7 '17 at 18:59











              • @kevswanberg - This Q&A was very difficult to find via a search. Would you consider expanding your answer to a generic example (such as: qs = Model1.objects.filter( attribute__in=Model2.objects.filter(##)) converted into your correct answer). As @TyrannoTaiwo and you both note, the error is thrown due to using a queryset within a queryset. But the error suggests slice as a problem - and searching around slices yields a lot of slicing a queryset type Q&A (making this specific use case issue difficult to find).

                – Bill Armstrong
                Jun 15 '18 at 5:02













              9












              9








              9







              Company is a queryset. You might want to do



              Product.objects.filter(company=company[0], pk=product_pk)


              Or better yet you can use the relations in the ORM to simplify into 1 lookup.



              Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk) 





              share|improve this answer













              Company is a queryset. You might want to do



              Product.objects.filter(company=company[0], pk=product_pk)


              Or better yet you can use the relations in the ORM to simplify into 1 lookup.



              Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk) 






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 7 '17 at 18:43









              kevswanbergkevswanberg

              1,359916




              1,359916












              • thanks, I didn't use [0] because I thought is just one result, but I presume is a list with one element

                – user3541631
                Dec 7 '17 at 18:47











              • filter returns a queryset, which is sliceable like a sequence. get is fine if you're sure that the pk exists, if it doesn't it'll throw an exception which you can catch and turn into a 404. Or if you're in a view, as it appears you are, you can use the get_object_or_404 shortcut: docs.djangoproject.com/en/1.11/topics/http/shortcuts/…

                – Peter DeGlopper
                Dec 7 '17 at 18:59











              • @kevswanberg - This Q&A was very difficult to find via a search. Would you consider expanding your answer to a generic example (such as: qs = Model1.objects.filter( attribute__in=Model2.objects.filter(##)) converted into your correct answer). As @TyrannoTaiwo and you both note, the error is thrown due to using a queryset within a queryset. But the error suggests slice as a problem - and searching around slices yields a lot of slicing a queryset type Q&A (making this specific use case issue difficult to find).

                – Bill Armstrong
                Jun 15 '18 at 5:02

















              • thanks, I didn't use [0] because I thought is just one result, but I presume is a list with one element

                – user3541631
                Dec 7 '17 at 18:47











              • filter returns a queryset, which is sliceable like a sequence. get is fine if you're sure that the pk exists, if it doesn't it'll throw an exception which you can catch and turn into a 404. Or if you're in a view, as it appears you are, you can use the get_object_or_404 shortcut: docs.djangoproject.com/en/1.11/topics/http/shortcuts/…

                – Peter DeGlopper
                Dec 7 '17 at 18:59











              • @kevswanberg - This Q&A was very difficult to find via a search. Would you consider expanding your answer to a generic example (such as: qs = Model1.objects.filter( attribute__in=Model2.objects.filter(##)) converted into your correct answer). As @TyrannoTaiwo and you both note, the error is thrown due to using a queryset within a queryset. But the error suggests slice as a problem - and searching around slices yields a lot of slicing a queryset type Q&A (making this specific use case issue difficult to find).

                – Bill Armstrong
                Jun 15 '18 at 5:02
















              thanks, I didn't use [0] because I thought is just one result, but I presume is a list with one element

              – user3541631
              Dec 7 '17 at 18:47





              thanks, I didn't use [0] because I thought is just one result, but I presume is a list with one element

              – user3541631
              Dec 7 '17 at 18:47













              filter returns a queryset, which is sliceable like a sequence. get is fine if you're sure that the pk exists, if it doesn't it'll throw an exception which you can catch and turn into a 404. Or if you're in a view, as it appears you are, you can use the get_object_or_404 shortcut: docs.djangoproject.com/en/1.11/topics/http/shortcuts/…

              – Peter DeGlopper
              Dec 7 '17 at 18:59





              filter returns a queryset, which is sliceable like a sequence. get is fine if you're sure that the pk exists, if it doesn't it'll throw an exception which you can catch and turn into a 404. Or if you're in a view, as it appears you are, you can use the get_object_or_404 shortcut: docs.djangoproject.com/en/1.11/topics/http/shortcuts/…

              – Peter DeGlopper
              Dec 7 '17 at 18:59













              @kevswanberg - This Q&A was very difficult to find via a search. Would you consider expanding your answer to a generic example (such as: qs = Model1.objects.filter( attribute__in=Model2.objects.filter(##)) converted into your correct answer). As @TyrannoTaiwo and you both note, the error is thrown due to using a queryset within a queryset. But the error suggests slice as a problem - and searching around slices yields a lot of slicing a queryset type Q&A (making this specific use case issue difficult to find).

              – Bill Armstrong
              Jun 15 '18 at 5:02





              @kevswanberg - This Q&A was very difficult to find via a search. Would you consider expanding your answer to a generic example (such as: qs = Model1.objects.filter( attribute__in=Model2.objects.filter(##)) converted into your correct answer). As @TyrannoTaiwo and you both note, the error is thrown due to using a queryset within a queryset. But the error suggests slice as a problem - and searching around slices yields a lot of slicing a queryset type Q&A (making this specific use case issue difficult to find).

              – Bill Armstrong
              Jun 15 '18 at 5:02













              9














              As said in the accepted answer, company is a queryset.



              The QuerySet value for an exact lookup must be limited to one result using slicing.


              Instead of this



              product = Product.objects.filter(company=company, pk=product_pk)


              try this



              product = Product.objects.filter(company__in=company, pk=product_pk)


              __in can handle querysets larger than one (multiple records of a table).



              This can be found in the django Many-to_one relationships section of the documentation.
              https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_one/



              Django documentation can be scary for a beginner like me because of its length and depth, though it provides solutions to most issues if you can crack it.






              share|improve this answer



























                9














                As said in the accepted answer, company is a queryset.



                The QuerySet value for an exact lookup must be limited to one result using slicing.


                Instead of this



                product = Product.objects.filter(company=company, pk=product_pk)


                try this



                product = Product.objects.filter(company__in=company, pk=product_pk)


                __in can handle querysets larger than one (multiple records of a table).



                This can be found in the django Many-to_one relationships section of the documentation.
                https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_one/



                Django documentation can be scary for a beginner like me because of its length and depth, though it provides solutions to most issues if you can crack it.






                share|improve this answer

























                  9












                  9








                  9







                  As said in the accepted answer, company is a queryset.



                  The QuerySet value for an exact lookup must be limited to one result using slicing.


                  Instead of this



                  product = Product.objects.filter(company=company, pk=product_pk)


                  try this



                  product = Product.objects.filter(company__in=company, pk=product_pk)


                  __in can handle querysets larger than one (multiple records of a table).



                  This can be found in the django Many-to_one relationships section of the documentation.
                  https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_one/



                  Django documentation can be scary for a beginner like me because of its length and depth, though it provides solutions to most issues if you can crack it.






                  share|improve this answer













                  As said in the accepted answer, company is a queryset.



                  The QuerySet value for an exact lookup must be limited to one result using slicing.


                  Instead of this



                  product = Product.objects.filter(company=company, pk=product_pk)


                  try this



                  product = Product.objects.filter(company__in=company, pk=product_pk)


                  __in can handle querysets larger than one (multiple records of a table).



                  This can be found in the django Many-to_one relationships section of the documentation.
                  https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_one/



                  Django documentation can be scary for a beginner like me because of its length and depth, though it provides solutions to most issues if you can crack it.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered May 24 '18 at 11:36









                  Tyranno TaiwoTyranno Taiwo

                  9327




                  9327





















                      0














                      This error can also be created when you pass a queryset for the value you are searching with.



                      Company.objects.filter(account=account, pk=company_pk) actually returns a queryset and that queryset can't be used in this query Product.objects.filter(company=company, pk=product_pk) without producing the error message.



                      What is really missing here is a .get, either like



                      company = Company.objects.filter(account=account, pk=company_pk).get()
                      or company = Company.objects.get(account=account, pk=company_pk)






                      share|improve this answer



























                        0














                        This error can also be created when you pass a queryset for the value you are searching with.



                        Company.objects.filter(account=account, pk=company_pk) actually returns a queryset and that queryset can't be used in this query Product.objects.filter(company=company, pk=product_pk) without producing the error message.



                        What is really missing here is a .get, either like



                        company = Company.objects.filter(account=account, pk=company_pk).get()
                        or company = Company.objects.get(account=account, pk=company_pk)






                        share|improve this answer

























                          0












                          0








                          0







                          This error can also be created when you pass a queryset for the value you are searching with.



                          Company.objects.filter(account=account, pk=company_pk) actually returns a queryset and that queryset can't be used in this query Product.objects.filter(company=company, pk=product_pk) without producing the error message.



                          What is really missing here is a .get, either like



                          company = Company.objects.filter(account=account, pk=company_pk).get()
                          or company = Company.objects.get(account=account, pk=company_pk)






                          share|improve this answer













                          This error can also be created when you pass a queryset for the value you are searching with.



                          Company.objects.filter(account=account, pk=company_pk) actually returns a queryset and that queryset can't be used in this query Product.objects.filter(company=company, pk=product_pk) without producing the error message.



                          What is really missing here is a .get, either like



                          company = Company.objects.filter(account=account, pk=company_pk).get()
                          or company = Company.objects.get(account=account, pk=company_pk)







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 7 at 23:22









                          boatcoderboatcoder

                          9,2921282135




                          9,2921282135



























                              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%2f47701679%2fissues-with-queryset-and-slicing%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

                              How to get text form Clipboard with JavaScript in Firefox 56?How to validate an email address in JavaScript?How do JavaScript closures work?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I copy to the clipboard in JavaScript?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

                              Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                              List of MPs elected to the English parliament in 1640 (April) Contents List of constituencies and members See also Notes References Navigation menueNational Archives – The Glynde Place ArchivesCobbett's Parliamentary history of England, from the Norman Conquest in 1066 to the year 1803'Aldermen in Parliament', The Aldermen of the City of London: Temp. Henry III – 1912onepage&q&f&#61, false 229