Django many to many MultipleObjectsReturned

    xiaoxiao2021-12-14  22

    使用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.

    转载请注明原文地址: https://ju.6miu.com/read-972023.html

    最新回复(0)