Suryan Boopathy
Suryan Boopathy

Reputation: 35

Django - Cannot access ManyToManyField item - Object has no attribute 'x'

enter image description here

class Cart(models.Model):
        user        = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE)
        products    = models.ManyToManyField(Product, blank=True)
        subtotal    = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
        total       = models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
        quantity    = models.IntegerField(default=0, null=True, blank=True)
        updated     = models.DateTimeField(auto_now=True)
        timestamp   = models.DateTimeField(auto_now_add=True)
    
    objects = CartManager()

    def __str__(self):
        return str(self.id)
    @property
    def get_total_item(self):
        total = self.products.price * self.quantity
        return total

class Product(models.Model):
    title           = models.CharField(max_length=120)
    slug            = models.SlugField(blank=True)
    description     = models.TextField()
    price           = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
    image           = models.ImageField(upload_to=upload_image_path,null=True, blank=True)
    featured        = models.BooleanField(default=False)
    active          = models.BooleanField(default=True)
    timestamp       = models.DateTimeField(auto_now_add=True)


    objects = ProductManager()



 @property
        def get_total_item(self):
            total = self.products.price * self.quantity
            return total
        (error in products,price how to access it )

In this self.products.price I cannot accesss the price from products.

I'm trying to retrieve multiple prices of product and quandity of individiual products.

I am trying to get a single value from product model but I dont know how to access that in many to many realtionships.

Upvotes: 2

Views: 287

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

self.products is a collection of Products, hence it has no .price, the Products individually have a price, but not the the collection.

You can sum up the prices, for example with:

from django.db.models import Sum

class Cart(models.Model):
    # …

    objects = CartManager()

    def __str__(self):
        return str(self.id)
    @property
    def get_total_item(self):
        return self.quantity * self.products.aggregate(
            total_price=Sum('price')
        )['total_price']

It is however a bit strange that you define the quantity on the Cart model. That means that the cart has a quantity, and thus that you can not create a cart with one product A, and two products B: either the quantity is one for all products, or two. Normally the quantity is stored in the **through=… model [Django-doc] of the ManyToManyField.

Upvotes: 2

Related Questions