gpt4 book ai didi

python - Django错误 "home.models.Friend.DoesNotExist: Friend matching query does not exist."

转载 作者:行者123 更新时间:2023-12-01 08:51:30 26 4
gpt4 key购买 nike

我的项目运行良好,直到我不得不卸载并重新安装 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)

还有我的主页 View 功能:

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')

导致此错误的原因是什么?如何修复它?

最佳答案

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

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

经理get method旨在精确检索一个对象:

If you know there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly

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

我怀疑您希望用户能够拥有零个 friend ,还是多个 friend ?使用 filter() method 而不是 get() :

friends = Friend.objects.filter(current_user=request.user)

无论current_user有多少 friend ,这都会起作用。

关于python - Django错误 "home.models.Friend.DoesNotExist: Friend matching query does not exist.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53085187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com