【问题标题】:Django - Cannot access ManyToManyField item - Object has no attribute 'x'Django - 无法访问 ManyToManyField 项目 - 对象没有属性“x”
【发布时间】:2020-07-02 10:44:48
【问题描述】:

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 )

在这个 self.products.price 中,我无法访问产品的价格。

我正在尝试检索产品的多个价格和单个产品的数量。

我正在尝试从产品模型中获取单个值,但我不知道如何在多对多关系中访问该值。

【问题讨论】:

    标签: django django-models django-rest-framework django-views


    【解决方案1】:

    self.productsProducts 的集合,因此它没有.priceProducts 单独有价格,但没有集合。

    您可以总结价格,例如:

    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']

    然而,在Cart 模型上定义quantity 有点奇怪。这意味着购物车有一个数量,因此您不能创建一个包含一个产品 A 和两个产品 B 的购物车:数量对于所有产品都是一个,或两个。通常数量存储在ManyToManyField**through=… model [Django-doc]中。

    【讨论】:

    • 试图将单个产品的价格和数量相乘
    • @SuryanBoopathy:但每个产品没有每个购物车的数量,只有每个购物车的数量。
    猜你喜欢
    • 1970-01-01
    • 2016-04-14
    • 2015-11-10
    • 2011-01-12
    • 2011-07-05
    • 2019-07-27
    • 1970-01-01
    相关资源
    最近更新 更多