Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't select related category in Django

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

AttributeError: ‘QuerySet’ object has no attribute ‘category’

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

>Solution :

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}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading