Home > database >  Can't select related category in Django
Can't select related category in Django

Time:07-20

I have 2 models with custom ProductManager

class ProductManager(models.Manager):
    def get_queryset(self):
        return super(ProductManager, self).get_queryset().filter(is_active=True)

class InnerCategory(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)

class Product(models.Model):
    name = models.CharField(max_length=70)
    category = models.ForeignKey(InnerCategory, null=True, on_delete=models.SET_NULL)
    slug = models.SlugField(unique=True)
    is_active = models.BooleanField(default=False)
    objects = models.Manager()
    products = ProductManager()

so i'm trying to get Product queryset and select related Category like so

queryset = Product.products.filter(
            category__slug=self.kwargs['category_slug']
            ).select_related('category')

print(queryset.category)

and when i try to run this page i get an error

AttributeError: 'QuerySet' object has no attribute 'category'

so how can i get all my Products and Categories in one query

CodePudding user response:

Your query seems to be correct and will fetch a subset of Products and their Categories. The query returns a QuerySet and you tried to access a non-existent attribute on it.

Depending on what you would like to do with your results, you could access them like this:

for product in queryset:
    print(f'{product.name} - {product.category.name}')
  • Related