0

我还有一个问题。如何解决?我是 Django 的初学者。

我的错误:

/magazines/“杂志”对象的 AttributeError 没有属性“items_set”

class Item(models.Model):
    name = models.CharField(max_length=50)
    item_price = models.DecimalField(max_digits=5, decimal_places=2)

class Magazine(models.Model):
    items = models.ManyToManyField('Item', blank=True, null=True)
    owner = models.ForeignKey(User, related_name='u_item')  

def show(request): #magazines items and total price of all items in this magazine
        user = request.user
        magazines = Magazine.objects.filter(owner=user)

        for m in Magazine.objects.filter(owner=user):
            total = m.items_set.all().annotate(total=Sum('item_price'))
            print 'Total cost for items in {0} is {1}'.format(m,total)


        return render_to_response('magazines.html', {'magazines': magazines, 'total': total})
4

2 回答 2

1

试试看嘛:

total = m.items.all().annotate(total=Sum('item_price'))
于 2012-09-28T11:07:11.007 回答
1

你不需要_set. 这不是反向关系:您在 Magazine 模型上直接拥有 manytomany 字段作为items.

total = m.items.all()...
于 2012-09-28T11:05:49.803 回答