如何在 Django 中使用其他模型获取模型对象

How to get model-objects using other models in django

我需要如果用户请求获取以下页面,则请求的响应将是包含由请求的用户关注的用户发布的特定帖子的页面。 我想采取一些行动来做到这一点:

  1. 获取请求者
  2. 获取请求者关注的用户
  3. 获取被关注用户创建的帖子

在我的 models.py:

class User(AbstractUser):
    image_url = models.CharField(max_length=5000, null=True)


class Follow(models.Model):
    follower = models.ForeignKey(
        User, on_delete=models.PROTECT, related_name="follower")
    following = models.ForeignKey(
        User, on_delete=models.PROTECT, related_name='following')


class Post(models.Model):
    content = models.CharField(max_length=140)
    date_created = models.DateTimeField(auto_now_add=True)
    poster = models.ForeignKey(User, on_delete=models.CASCADE)

在我的 views.py:

def following_page(request, username):
    user = User.objects.get(username=username)
    f = user.following.all()
    posts = Post.objects.filter(poster=f.following)
    posts = posts.order_by("-date_created").all()
    return render(request, 'network/index.html', {
        "posts": posts
    })

它说

AttributeError 'QuerySet' object has no attribute 'following'

我需要更换模型吗?如何解决问题?

您可以过滤:

from django.contrib.auth.decorators import <strong>login_required</strong>

<strong>@login_required</strong>
def following_page(request):
    posts = Post.objects.filter(<strong>poster__following__follower=request.user</strong>)
    return render(request, 'network/index.html', {
        'posts': posts
    })

由于您使用的是登录用户,因此使用的是 request.user,因此视图接受用户名是没有意义的。


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.