Django many to many MultipleObjectsReturned

使用DJANGO按栏目名输出栏目文章列表,返回

百思不得其其解释,从下面的文章MANY TO MANY 查询中得到启发
view.py中启用model.py查询

单个查询用get
类别查询用filter

不然就会出现

get() returned more than one Article -- it returned 16!

下面是原文复制文档:
Let’s say that I have a blog entry with multiple tags. The tags field is a ManyToMany in my model. I want to take all blog entries and for each entry I want to get all tags.

Basically I would do something like that

entries = Entries.objects.get(author=user)
for entry in entries:
     tags[entry.pk] = entry.tags.all()

The problem is that I get the MultipleObjectsReturned error.

ANSWER:
If you want to return all entries with author=user, then use filter()

entries = Entries.objects.filter(author=user)

At the moment, you are using get(), w**hich expects to return one Entries object. As there is more that one Entries with author=user**, you get the Entries.MultipleObjectsReturned error.

Note, with Django, the convention is to use the singular name Entry for your model, instead of the plural Entries.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值