[英]Object has no attribute 'items_set'. Django orm
我有另一个问题。 怎么解决? 我是Django的初学者。
我的错误:
/ magazines /'Magazine'对象的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})
你不需要_set
。 这不是一种向后的关系:你可以直接在Magazine模型上将多个字段作为items
。
total = m.items.all()...
你试一试:
total = m.items.all().annotate(total=Sum('item_price'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.