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
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With