Python 字段';id';应为一个数字,但得到';纳苏';德扬戈
我想创建一个user_posts视图,其中包含与特定用户相关的所有帖子,比如说有/有由用户“Natsu”撰写的博客帖子,然后登录用户(比如“Testuser”)将能够看到该用户的所有帖子,即用户“Natsu”的所有帖子Python 字段';id';应为一个数字,但得到';纳苏';德扬戈,python,django,foreign-keys,valueerror,Python,Django,Foreign Keys,Valueerror,我想创建一个user_posts视图,其中包含与特定用户相关的所有帖子,比如说有/有由用户“Natsu”撰写的博客帖子,然后登录用户(比如“Testuser”)将能够看到该用户的所有帖子,即用户“Natsu”的所有帖子 blog models.py class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_dat
blog models.py
class Post(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to='profile_pic', default='default.jpg')
def __str__(self):
return f'{ self.user.username } Profile'
def user_posts(request, username):
posts = Post.objects.filter(author=username)
return render(request, 'blog/user_posts.html', {'posts':posts})
path('user/<str:username>/', views.user_posts, name='user-posts'),
user models.py
class Post(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to='profile_pic', default='default.jpg')
def __str__(self):
return f'{ self.user.username } Profile'
def user_posts(request, username):
posts = Post.objects.filter(author=username)
return render(request, 'blog/user_posts.html', {'posts':posts})
path('user/<str:username>/', views.user_posts, name='user-posts'),
views.py
class Post(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to='profile_pic', default='default.jpg')
def __str__(self):
return f'{ self.user.username } Profile'
def user_posts(request, username):
posts = Post.objects.filter(author=username)
return render(request, 'blog/user_posts.html', {'posts':posts})
path('user/<str:username>/', views.user_posts, name='user-posts'),
user\u posts.html
{% for post in posts %}
<a href="{% url 'user-posts' post.author.username %}" class="mr-2">{{ post.author }}</a>
<h2><a href="{% url 'post-detail' post.pk %}">{{ post.title }}</a></h2>
{{ post.body|truncatewords:30 }}
{% endfor %}
但当我转到该url时,它会显示错误字段“id”需要一个数字,但得到了“admin”。
这里有完整的回溯:
Internal Server Error: /user/natsu/
Traceback (most recent call last):
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'natsu'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Sheraram Prajapat\OneDrive\Desktop\Virtual Environment\mysite\blog\views.py", line 78, in user_posts
posts = Post.published.filter(author=username)
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1311, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\lookups.py", line 22, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in
get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got 'natsu'.
[29/Jun/2020 17:47:37] "GET /user/natsu/ HTTP/1.1" 500 127097
我哪里做错了?还有其他选择吗
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
由于您在auhor字段中使用了foreignkey,我认为您无法通过posts=Post.objects.filter(author=username)
对其进行过滤。你能试试过滤(author=user.id)吗
由于您在auhor字段中使用了foreignkey,我认为您无法通过
posts=Post.objects.filter(author=username)
对其进行过滤。你能试试filter(author=user.id)
吗?Post上的author
将是user
表的主键,它是一个整数(除非从默认值修改),而不是用户名。您需要首先查找用户名
是用户
,或者使用其他Django“魔术”。也许可以尝试其中一种(我认为它们在后端都做相同的事情):
posts=Post.objects.filter(author=User.object.filter(username=username)[:1])
或
posts=Post.objects.filter(作者\用户名=用户名)
(我也没有测试…因此,如果其中任何一个不起作用,请自由编辑此答案或评论)Post上的作者
将是用户
表的主键,该表是一个整数(除非从默认值修改),而不是用户名
。您需要首先查找用户名
是用户
,或者使用其他Django“魔术”。也许可以尝试其中一种(我认为它们在后端都做相同的事情):
posts=Post.objects.filter(author=User.object.filter(username=username)[:1])
或
posts=Post.objects.filter(作者\用户名=用户名)
(我也没有测试过…所以请自由编辑此答案或评论,如果其中任何一个都不起作用)
或
或
您可以执行类似于Post.objects.filter(author\uu username=username)
@Tim Tisdall的操作,谢谢。Post.objects.filter(author\u username=username)按预期工作@mattarello请您解释一下我如何传递写过博客的人的用户id?为此,您必须将路径更改为path('user/',views.user_posts,name='user-posts')。在视图中进行如下修改:(请求、用户名、id):@TimTisdall的解决方案要好得多,我会坚持下去。唯一的问题是,username
通常用于登录,而你会通过URL公开它。此外,您可能需要测试用户名包含“/”时会发生什么。您可以执行类似于Post.objects.filter(author\uu username=username)
@Tim Tisdall的操作,谢谢。Post.objects.filter(author\u username=username)按预期工作@mattarello请您解释一下我如何传递写过博客的人的用户id?为此,您必须将路径更改为path('user/',views.user_posts,name='user-posts')。在视图中进行如下修改:(请求、用户名、id):@TimTisdall的解决方案要好得多,我会坚持下去。唯一的问题是,username
通常用于登录,而你会通过URL公开它。此外,您可能需要测试用户名包含“/”时会发生什么情况。请注意,第一个选项需要双重查询。@Tim Tisdall,posts=Post.objects.filter(author=User.object.filter(username=username)),这会导致错误“精确查找的QuerySet值必须使用切片限制为一个结果。”我认为第一个可能是Post.objects.filter(author=User.object.filter(username=username)[:1])
,但第二个更具可读性。@mattarello-第一个是由于延迟加载而产生的单个查询。Django认识到它可以通过一个子查询处理这个问题,并且它通过一个子查询执行单个查询。(我没有特别检查,但我非常确定它在两个版本中都是这样工作的;使用子查询)注意,第一个选项需要双重查询。@Tim Tisdall,posts=Post.objects.filter(author=User.object.filter(username=username)),这会导致错误“精确查找的QuerySet值必须限制为使用切片的一个结果。”我认为第一个可能是Post.objects.filter(author=User.object.filter(username=username)[:1])
,但第二个更具可读性。@mattarello-第一个是由于延迟加载而产生的单个查询。Django认识到它可以通过一个子查询处理这个问题,并且它通过一个子查询执行单个查询。(我没有特别检查,但我很确定这是它在两个版本中的工作方式;使用子查询)。。。你刚才重复了我的答案(后来我改正了错误)。。。你刚才重复了我的答案(后来我改正了错误)