Django:'经理'对象没有属性' get_quantity_sum'

时间:2015-11-04 12:17:12

标签: python django

我在我的模型中创建了一个检查网店应用库存余额的方法。

models.py:

class ProductVariantSize(models.Model):
    product_variant = models.ForeignKey('ProductVariant', related_name='sizes')
    size = models.ForeignKey('Size')
    available_qty = models.IntegerField(default=0)

    def __unicode__(self):
        return u'%s %d kom' % (lang.resolve_dict(self.size.name), self.available_qty)

    def stock_check(self):
        from webshop.models import OrderDetail

        sold_sum = OrderDetail.objects.filter(
            variant=self.product_variant, size = self.size).aggregate(
            total_quantity=Sum('quantity'))['total_quantity']
        receipt_sum = ReceiptDetail.objects.filter(
            variant=self.product_variant, size = self.size).aggregate(
            total_quantity=Sum('quantity'))['total_quantity']
        bill_of_lading_sum = BillOfLadingDetail.objects.filter(
            variant=self.product_variant, size = self.size).aggregate(
            total_quantity=Sum('quantity'))['total_quantity']
        stock_return_sum = StockReturnDetail.objects.filter(
            variant=self.product_variant, size = self.size).aggregate(
            total_quantity=Sum('quantity'))['total_quantity']

        total_sum = receipt_sum - sold_sum - bill_of_lading_sum - stock_return_sum
        if self.available_qty != total_sum:
            return False
        return True

正如您所看到的,我的查询集过滤器都是相同的。我想在这里使用django自定义管理器,但我似乎无法让它工作。以下是我尝试过的内容:

class SumManager(models.Manager):
    def get_quantity_sum(self):
        qs = self.get_queryset()
        return qs.filter(
            variant=self.product_variant, size = self.size).aggregate(
            total_quantity=Sum('quantity'))['total_quantity']


class ProductVariantSize(models.Model):
    product_variant = models.ForeignKey('ProductVariant', related_name='sizes')
    size = models.ForeignKey('Size')
    available_qty = models.IntegerField(default=0)

    objects = SumManager()

    def __unicode__(self):
        return u'%s %d kom' % (lang.resolve_dict(self.size.name), self.available_qty)

    def stock_check(self):
        from webshop.models import OrderDetail

        sold_sum = OrderDetail.objects.get_quantity_sum()
        receipt_sum = ReceiptDetail.objects.get_quantity_sum()
        bill_of_lading_sum = BillOfLadingDetail.objects.get_quantity_sum()
        stock_return_sum = StockReturnDetail.objects.get_quantity_sum()

        total_sum = receipt_sum - sold_sum - bill_of_lading_sum - stock_return_sum
        if self.available_qty != total_sum:
            return False
        return True

我一直收到以下错误:

  

'管理器'对象没有属性' get_quantity_sum'

1 个答案:

答案 0 :(得分:2)

您需要在要使用它的模型上定义自定义管理器。因此,在您的代码中,您在f(y,s,C,u,v)上定义了objects = SumManager(),但是您尝试在所有其他模型上调用ProductVariantSize方法SumManager(例如get_quantity_sum())。

如果您想致电OrderDetail,则需要在OrderDetail.objects.get_quantity_sum()

上定义自定义管理员