Django错误“ home.models.Friend.DoesNotExist:朋友匹配查询不存在。”

时间:2018-10-31 13:59:22

标签: python django

在必须卸载并重新安装MySQL数据库并重新迁移/重新创建数据之前,我的项目运行良好。

现在,当我导航到/home/时会引发此错误

DoesNotExist at /home/
Friend matching query does not exist. 

该查询确实存在于数据库中,并且所有其他页面均可工作。

从命令行:

 Internal Server Error: /home/
    Traceback (most recent call last):
      File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
        response = get_response(request)
      File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view
        return self.dispatch(request, *args, **kwargs)
      File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/views/generic/base.py", line 88, in dispatch
        return handler(request, *args, **kwargs)
      File "/Users/trillav/apps/max/home/views.py", line 16, in get
        friend = Friend.objects.get(current_user=request.user)
      File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "/Users/trillav/.virtualenvs/max/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
        self.model._meta.object_name
    home.models.Friend.DoesNotExist: Friend matching query does not exist.
    [31/Oct/2018 13:53:02] "GET /home/ HTTP/1.1" 500 81063

这里是home.models

from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    post = models.CharField(max_length=500)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

class Friend(models.Model):
    users = models.ManyToManyField(User)
    current_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner', null=True)

    @classmethod
    def make_friend(cls, current_user, new_friend):
        friend, created = cls.objects.get_or_create(
            current_user=current_user
        )
        friend.users.add(new_friend)

    @classmethod
    def lose_friend(cls, current_user, new_friend):
        friend, created = cls.objects.get_or_create(
            current_user=current_user
        )
        friend.users.remove(new_friend)

我的主视图功能:

from django.views.generic import TemplateView
from django.shortcuts import render, redirect
from django.contrib.auth.models import User

from home.forms import HomeForm
from home.models import Post, Friend

# Create your views here.
class HomeView(TemplateView):
    template_name = 'home/home.html'

    def get(self, request):
        form = HomeForm()
        posts = Post.objects.all().order_by('-created')
        users = User.objects.exclude(id=request.user.id)
        friend = Friend.objects.get(current_user=request.user)
        friends = friend.users.all()

        args = {
            'form': form, 'posts': posts, 'users': users, 'friends': friends
        }
        return render(request, self.template_name, args)

    def post(self, request):
        form = HomeForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            text = form.cleaned_data['post']
        return redirect('home:home')

        args = {'form': form, 'text': text}
        return render(request, self.template_name, {'form': form})

def change_friends(request, operation, pk):
    friend = User.objects.get(pk=pk)
    if operation == 'add':
        Friend.make_friend(request.user, friend)
    elif operation == 'remove':
        Friend.lose_friend(request.user, friend)
    return redirect('home:home')

是什么原因导致此错误,该如何解决?

1 个答案:

答案 0 :(得分:1)

在您的回溯中提到了views.py中的第16行。它是这样的:

friend = Friend.objects.get(current_user=request.user)

Manager的{​​{3}}用于精确地检索一个对象:

  

如果您知道只有一个对象与您的查询匹配,则可以在get method上使用get()方法,该方法将直接返回该对象

如果您的查询检索到其他任何数量的对象,则会引发异常(此处为DoesNotExist-Friend.DoesNotExist的特定于模型的子类,如果返回了零个对象,而子类为{{1} }(如果返回多个)。

我怀疑您希望用户能够拥有零个朋友或一个以上的朋友?使用Manager代替MultipleObjectsReturned

get()

无论friends = Friend.objects.filter(current_user=request.user) 有多少朋友,这都行得通。