Search code examples
djangodjango-class-based-viewsdjango-generic-views

Accessing foreign key values in django ListView of GCBV


I have two models related by a Foreign key as follows. (Only shown important fields here.)

in model:

class Category(models.Model):
    name = models.CharField(max_length=50, unique=True)
    description = models.TextField()
    ...

class Price(models.Model):
    category = models.ForeignKey(Category) # referred to above model
    sub_type = models.CharField(max_length=4, choices=CHOICE_SUB_TYPE)
    price = models.DecimalField()
    ...

I'm going to display Categories in a ListView along with related pricing details. In order do that, I need to set related pricing objects for each Category object. What is the best and efficient way to do this?


Solution

  • Your code is fine as it is, in templates, you have access to related models. When listing categories in your template you can:

    <ul>
    {% for cat in categories %}
       <li>{{ cat.name }}</li>
       <ul>
           {% for price in cat.price_set.all %}
               {{ price.price }}
           {% endfor %}
       </ul>
    
    {% endfor %}
    </ul>
    

    For displaying categories when showing details for a price, you might want to Use a Single object Mixin with a ListView.

    Recommended: Related object reference.