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

                              Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                              Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                              How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page