byrdr
byrdr

Reputation: 5477

Django object has no attribute 'all'

I have a query on foreign key field that is returning the following error.

'Category' object has no attribute 'all'

Here is my query:

p = get_object_or_404(Product, slug=product_slug)
categories = p.categories.all()

Based on these models:

class Category(models.Model):
  name = models.CharField(max_length=50)
  slug = models.SlugField(max_length=50,  unique=True, help_text='Unique value from product page URL, created from name')
  is_active = models.BooleanField(default=True)
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)

class Product(models.Model):
  name = models.CharField(max_length=255, unique=True)
  slug = models.SlugField(max_length=255, unique=True, help_text='Unique value for product page URL, created from name')
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)
categories = models.ForeignKey(Category, null=True)

I understand the issue is a result of the foreign key referencing only one model; however, when I try to run:

categories = p.categories

I return the following error:

'Category' object is not iterable

I'm not sure how to resolve this issue.

Upvotes: 0

Views: 1172

Answers (1)

aerivero.m
aerivero.m

Reputation: 131

You should use a different approach for your relationships. The way I see your code you should have a ManytoMany relationship since one product may belongs to N categories and one category may have N products attached to it.

Check this ManyToManyField

Anyway try to change this in your Product model:

categories = models.ManyToManyField(Category, null=True)

Upvotes: 1

Related Questions