Home > OS >  Django relations nesting "related_name"
Django relations nesting "related_name"

Time:12-07

I'm trying to create single loop that will iterate through all sizes for each product from category. My models:

class Category(models.Model):
    ...

class Product(models.Model):
    category = models.ForeignKey(Category, db_column="id", on_delete=models.CASCADE, related_name="products")
    ...

class Size(models.Model):
    product = models.ForeignKey(Product, db_column="id", on_delete=models.CASCADE, related_name="sizes")
    ...

And my code in service

def adjust_sizes(self, category: Category) -> None:
    for size in category.products.sizes.all():
        # rest of my function

But when I was trying to run this function I got error:

*** AttributeError: 'RelatedManager' object has no attribute 'sizes'

I wanted this to run in single loop, can someone help me how to do that?

CodePudding user response:

You can't access the manager on top of a manager. What you do in this case is query in reverse, so:

def adjust_sizes(self, category: Category) -> None:
    for size in Size.objects.filter(product__category=category):
        # rest of my function
        pass

Very likely using db_column='id' is however not a good idea, since it can/will clash with the database column for the primary key.

CodePudding user response:

lass Category(models.Model):
    ...

class Product(models.Model):
    category = models.ForeignKey(Category, db_column="id", on_delete=models.CASCADE, related_name="products")
    ...

class Size(models.Model):
    product = models.ForeignKey(Product, db_column="id", on_delete=models.CASCADE, related_name="sizes")
    ...
  • Related