Django Get Returns More than one value

时间:2021-05-12 14:31:27

标签: python html python-3.x django

你好,我是 django 的新手,我正在制作一个博客网站,当我尝试访问我的博客时出现错误 我的代码: 视图.py:

from django.http import request
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Item, Blog

# Create your views here.
class BlogView(ListView):
    model = Blog
    template_name = "main/blog.html"
    context_object_name = "blog"

    def get_context_data(self, **kwargs):
        context =  super().get_context_data(**kwargs)
        search_input = self.request.GET.get('search') or ''
        if search_input:
            context['blog'] = context['blog'].filter(title__icontains=search_input)
        return context


class Detail(DetailView):
    model = Item
    template_name = "main/item.html"
    context_object_name = "items"

    def get_context_data(self, **kwargs):
        context =  super().get_context_data(**kwargs)
        obj = Item.objects.get()
        context['items'] = Item.objects.filter(blog_id=obj.blog_id)
        return context

models.py:

from django.db import models

# Create your models here.
class Blog(models.Model):
    title = models.CharField(max_length=200)
    image = models.ImageField(null=True, blank=True)
    created = models.DateField(auto_now_add=True, null=True)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['created']
    
    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ""
        return url
        
class Item(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(max_length=1000)
    image = models.ImageField(null=True, blank=True)
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
    
    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ""
        return url

对于此错误的任何帮助将不胜感激:

MultipleObjectsReturned at /detail/2/
get() returned more than one Item -- it returned 2!
Request Method: GET
Request URL:    http://127.0.0.1:5000/detail/2/
Django Version: 3.2
Exception Type: MultipleObjectsReturned
Exception Value:    
get() returned more than one Item -- it returned 2!
Exception Location: /home/moeez/.local/lib/python3.8/site-packages/django/db/models/query.py, line 439, in get
Python Executable:  /usr/bin/python3
Python Version: 3.8.5
Python Path:    
['/home/moeez/Python Projects/blogsite',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/moeez/.local/lib/python3.8/site-packages',
 '/usr/local/lib/python3.8/dist-packages',
 '/usr/local/lib/python3.8/dist-packages/buildozer-1.2.0.dev0-py3.8.egg',
 '/usr/local/lib/python3.8/dist-packages/virtualenv-20.4.3-py3.8.egg',
 '/usr/local/lib/python3.8/dist-packages/sh-1.14.1-py3.8.egg',
 '/usr/local/lib/python3.8/dist-packages/filelock-3.0.12-py3.8.egg',
 '/usr/local/lib/python3.8/dist-packages/distlib-0.3.1-py3.8.egg',
 '/usr/local/lib/python3.8/dist-packages/appdirs-1.4.4-py3.8.egg',
 '/usr/lib/python3/dist-packages']
Server time:    Wed, 12 May 2021 14:31:09 +0000

2 个答案:

答案 0 :(得分:0)

问题是您使用的是没有参数的 function encodeParam<T extends {}>(urlParam: UrlParam<T>, value: T) { return value !== undefined && value !== null ? urlParam.encode(value) : null // okay } 。您应该以与 Item.objects.get() 相同的方式使用 get,但 filter 可能返回仅一个对象,而 get 可能返回一个查询集。

例如:

filter

答案 1 :(得分:0)

在使用 get 方法时,您应该使用保证唯一的查找,例如唯一约束中的主键或字段,如果 get() 方法返回多个对象,则会引发一个模型。MultipleObjectsReturned 与您的情况一样的异常 Item.objects.get() 找到 1 个以上的对象并引发异常。

为了解决这个问题,将从 url 捕获的 pk 传递给 get 方法。您可以从 kwargs 字典中使用名为 'pk' 的键访问相同的内容。

更改代码中的行:

obj = Item.objects.get() 

致:

obj = Item.objects.get(id=self.kwargs.get('pk'))
相关问题