Django:访问模型上的related_name返回None

woobm2wo  于 2022-12-20  发布在  Go
关注(0)|答案(1)|浏览(122)

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文件定义了Userpost之间的关系,如下所示:

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行)?据我理解,这两个语句应该实现相同的事情?
4c8rllxm

4c8rllxm1#

.posts是一个Manager,不是一个QuerySet,你可以使用**.all()**[Django-doc],把它变成一个QuerySet

from django.contrib.auth.decorators import login_required

@login_required
def profile(request, username):
    print(User.objects.get(username=username).posts.all())
    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)},
    )

Note:您可以使用**@login_required**decorator [Django-doc]将视图限制为只对经过身份验证的用户开放。

相关问题