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

Djnago relations nesting "related_name"

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:

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: 'RelatedManager' object has no attribute 'sizes'

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

>Solution :

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.

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