Help On Accessing Many To many

Hi,

I have the below models, I am trying to access them in the model by pulling the prices in via the view.

from django.db import models
from django.contrib.auth.models import Group, User


class Features(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name
class Product(models.Model):
    name = models.CharField(max_length=100)
    stripe_product_id = models.CharField(max_length=100)
    Permissiongroup = models.ManyToManyField(Group)
    feature = models.ManyToManyField(Features, related_name='features')

    def __str__(self):
        return self.name

class Price(models.Model):
    name = models.CharField(max_length=100)
    product = models.ForeignKey(Product, on_delete=models.CASCADEm related_name="price")
    stripe_price_id = models.CharField(max_length=100)
    price = models.IntegerField(default=0)  # cents
    BillFrequency = models.CharField(max_length=50)

    def get_display_price(self):
        return "{0:.2f}".format(self.price)

Template

   {% for price in prices %}
                {% if price.BillFrequency == "Monthly" %}
                <div class="col-md-4">
                    <div {% if "Premium" not in price.product %} class="inner holder active" {% else %}class="inner holder" {% endif %} >
                        <div class="hdng">
                            <p>{{price.product}}</p>
                        </div>
                        <div class="price mt-5">
                            <p><b>£{{ price.get_display_price }}</b><span> / mo</span></p>
                        </div>
                        <div class="info">
                        **{{ price.Product.features }}**

My view is just pulling all the prices in (Price.objects.all)

Am I able to access and iterate through the features for the product by just calling in the Price via reverse lookups on the foreign key? Or do I need more in the view to pull it in

Thanks
Rob

If product is an instance of Product, then product.feature is a related object manager to Features. This manager is like any other manager - it still expects a queryset function be applied to retrieve the instances.

In this case, if you want all features, then product.feature.all yields all instances of Features that are related to product. If you iterate over that queryset, such as using {% for feature in product.feature.all %}, then {{ feature.name }} would render the name of that feature.

If price is an instance of Price, then price.product is an instance of Product.

Combining these two then means you could iterate over price.product.feature.all to get the names of the features for each price.

Having said all this, if you’re iterating over multiple price instances, you probably want to add the appropriate usages of select_related and prefetch_related to the queries being issued in the view to minimize the number of queries being issued to the database.