1

I have the following code:

  company = Company.objects.filter(account=self.account).only('slug')
        if company:
            return redirect(reverse_lazy('company:detail_a', kwargs={'slug': company.slug}))

I get the error:

'QuerySet' object has no attribute 'slug'

The slug attribute definitely exist(checked in model/database). I tried to access it like in a template.

So I tried with other attributes, 'name', because appears when I print the QuerySet.

So I think the QuerySet is not evaluated or something like that, but I don't know how to force to do it.

3 Answers 3

3

A QuerySet is a collection of instances. The collection doesn't have any of those attributes; only the individual instances do.

If you want to get an individual instance, use get instead of filter.

Sign up to request clarification or add additional context in comments.

Comments

1

filter will return a query set not a model object if you want a single object not a queryset try filter with first

  company = Company.objects.filter(account=self.account).only('slug').first()
  if company:
      return redirect(reverse_lazy('company:detail_a', kwargs={'slug': company.slug}))

OR

company = Company.objects.only('slug').get(account=self.account)
  if company:
      return redirect(reverse_lazy('company:detail_a', kwargs={'slug': company.slug}))

Comments

0

if you try to use it on a detail-page try this:

 <a href="{{ object.get_add_to_cart_url }}" class="cart-btn">Add to cart</a>

instead of:

    <a href="{{ item.get_add_to_cart_url }}" class="cart-btn">Add to cart</a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.