Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with queryset and slicing

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

like image 598
user3541631 Avatar asked Dec 07 '17 18:12

user3541631


2 Answers

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.

like image 54
Tyranno Taiwo Avatar answered Nov 17 '22 01:11

Tyranno Taiwo


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) 
like image 18
kevswanberg Avatar answered Nov 17 '22 01:11

kevswanberg