models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class Likes(models.Model):
pass
class Unlikes(models.Model):
pass
class Post(models.Model):
post_text = models.TextField(max_length=1000)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
likes = models.ManyToManyField(User, null=True, related_name="liked_posts")
unlikes = models.ManyToManyField(User, null=True, related_name="unliked_posts")
def __str__(self):
return f'{self.user} at {self.created_at}: {self.post_text[0:20]}...'
views.py
def profile(request, username):
print(User.objects.get(username=username).posts)
print(Post.objects.filter(user = User.objects.get(username=username)))
return render(request, 'network/profile.html', {
'user': request.user,
'profile': User.objects.get(username=username)
})
我的models.py
文件定义了User
和post
之间的关系,如下所示:
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
运行:
print(User.objects.get(username=username).posts)
print(Post.objects.filter(user = User.objects.get(username=username)))
退货:
network.Post.None
<QuerySet [<Post: Joe at 2022-12-18 10:48:18.941880+00:00: test1...>, <Post: Joe at 2022-12-18 10:53:27.407349+00:00: test1...>, <Post: Joe at 2022-12-18 10:53:34.167508+00:00: test2...>]>
- 我的问题:**第一个print语句怎么可能不返回行,而第二个语句返回期望值(3行)?据我理解,这两个语句应该实现相同的事情?
1条答案
按热度按时间4c8rllxm1#
.posts
是一个Manager
,不是一个QuerySet
,你可以使用**.all()
**[Django-doc],把它变成一个QuerySet
:Note:您可以使用**
@login_required
**decorator [Django-doc]将视图限制为只对经过身份验证的用户开放。