【问题标题】:Get all post from users which my user follow从我的用户关注的用户那里获取所有帖子
【发布时间】:2021-01-04 14:08:08
【问题描述】:

我想获取我的用户关注的所有用户的所有帖子。

我的用户模型看起来像

from django.db import models
from django.contrib.auth.models import AbstractUser
from apps.friend_request.models import FriendRequest


# Save avatar to user specific directory in media files
def user_avatar_directory(instance, filename):
    return f'{instance.username}/avatar/{filename}'


class User(AbstractUser):
    # Field that is used as the unique identifier
    USERNAME_FIELD = 'email'

    # Fields that are required when using createsuperuser (username_field and password fields are required by default)
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    # Fields that shall be treated as public and can be exposed to all logged-in users
    PUBLIC_FIELDS = ('id', 'username', 'first_name', 'last_name', 'country')

    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    country = models.CharField(max_length=150, blank=True, null=True)
    city = models.CharField(max_length=150, blank=True, null=True)
    about = models.TextField(blank=True, null=True)
    avatar = models.ImageField(upload_to=user_avatar_directory, blank=True, null=True)
    followers = models.ManyToManyField(to='self', symmetrical=False, related_name='followees', blank=True)

我的帖子模型

from django.db import models
from django.conf import settings


class Post(models.Model):
    user = models.ForeignKey(
        #to=User,
        to=settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='posts',
        #null=True
    )
    content = models.CharField(
        max_length=150,
        blank=False
    )
    created = models.DateTimeField(
        auto_now=True
    )
    liked_by = models.ManyToManyField(
         #to=User,
         to=settings.AUTH_USER_MODEL,
         related_name='liked_posts',
         blank=True
    )

    # TODO
    # comments = Set('Comment')

    # TODO sharing not yet clear what it is about
    # shared = Optional('Post', reverse='sharing')
    # sharing = Set('Post', reverse='shared')

    def __str__(self):
        return f'ID: {self.pk}: {self.content} '

class Post_Pic(models.Model):
    created = models.DateTimeField(
        auto_now=True
    )
    post_id = models.ForeignKey(
        to=Post,
        on_delete=models.CASCADE,
        related_name='posts',
    )
    image = models.ImageField(
        upload_to='post_pic'
    )

    def __str__(self):
        return f'ID: {self.pk} Post: {self.post_id} File: {self.image.name}'

我的意见.py

class MyFollowersPosts(ListView):
    """
    Get all followers
    """
    queryset = Post.objects.all()
    serializer_class = FollowesSerilizer

    def get_queryset(self):
        posts = []
        for user in self.request.user.followers.all():
            for post in Post.objects.filter(author=user.followed):
                posts.append(post)

        return posts 

问题是我总是收到这个错误,我找不到问题出在哪里

AttributeError at /backend/api/social/posts/following/ 'AnonymousUser' 对象没有属性 'followers' 请求方法:GET 请求网址:http://127.0.0.1:8000/backend/api/social/posts/following/ Django 版本:3.1.4 异常类型:属性错误 异常值:
'AnonymousUser' 对象没有属性 'followers' 异常位置:C:\Users\Dell\anaconda3\envs\motion-backend\lib\site-packages\django\utils\functional.py,第 241 行,在内部 Python 可执行文件:C:\Users\Dell\anaconda3\envs\motion-backend\python.exe Python版本:3.9.1 Python 路径:
['C:\Users\Dell\Desktop\day-5-django-motion-assignment', 'C:\Users\Dell\anaconda3\envs\motion-backend\python39.zip', 'C:\Users\Dell\anaconda3\envs\motion-backend\DLLs', 'C:\Users\Dell\anaconda3\envs\motion-backend\lib', 'C:\Users\Dell\anaconda3\envs\motion-backend', 'C:\Users\Dell\anaconda3\envs\motion-backend\lib\site-packages'] 服务器时间:2021 年 1 月 4 日星期一 13:53:46 +0000

【问题讨论】:

    标签: python django-models django-rest-framework django-views


    【解决方案1】:

    您的get_queryset 应该返回QuerySet,而不是列表。此外,您不需要通过循环获取项目,您可以通过以下方式查询:

    from rest_framework.permissions import IsAuthenticated
    
    class MyFollowersPosts(ListView):
        # …
        permission_classes = [IsAuthenticated]
        
        def get_queryset(self):
            return Post.objects.filter(author__followees=self.request.user)

    此外,用户应该登录。您可以使用 IsAuthenticated 权限类来执行此操作。

    【讨论】:

      猜你喜欢
      • 2019-01-22
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多