【问题标题】:Django: Unsupported lookup 'following' for CharField or join on the field not permittedDjango:CharField 的不支持查找“以下”或不允许加入该字段
【发布时间】:2021-02-24 14:12:53
【问题描述】:

我尝试构建关注系统,当我尝试让用户查看关注他们的用户的帖子时,我收到错误 Unsupported lookup 'following' for CharField or join on the field not allowed

配置文件模型

class Account(AbstractBaseUser):
    email = models.EmailField(verbose_name="email", max_length=60, unique=True)
    username = models.CharField(max_length=30, unique=True)
    date_joined = models.DateTimeField(
        verbose_name="date joined", auto_now_add=True
    )
    following = models.ManyToManyField(
        settings.AUTH_USER_MODEL, blank=True, related_name="follow"
    )

帖子模型

class Video(models.Model):
    author = models.ForeignKey(Account, on_delete=models.CASCADE)
    video = models.FileField(upload_to='post-videos')
    title = models.CharField(max_length=100)
    description = models.TextField(null=True, blank=True)

我的看法

class home_screen_view(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        logged_in_user = request.user
        post = Video.objects.filter(
            author__username__following__in=[logged_in_user.id]
        ).order_by('-created_date')
        context = {
            'post_list': post,
        }
        return render(request, "personal/home.html", context)

【问题讨论】:

    标签: django django-models django-views django-templates


    【解决方案1】:

    您的post = ... 查询是错误的,因为您正在检索作者的username(存在),但随后将此字段视为外键或带有属性的m2m,这是完全错误的。用户名是一个 CharField。

    相反,让我们尝试澄清有助于制定我们的解决方案的概念:

    每个视频都有一个作者。

    每个作者都是用户。

    每个用户都有一个m2m关系following,即他关注的用户。

    每个用户都有一个反向 m2m 关系follow,即关注他的用户。

    因此,在您看来,您的查询应该是:

        post = Video.objects.filter(
            author__follow=logged_in_user
        ).order_by('-created_date')
    

    使用 django M2Ms,只要 logged_in_user 在该列表中,...follow=logged_in_user 将返回 true 并过滤项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-26
      • 2019-06-01
      • 1970-01-01
      • 2018-08-04
      • 2022-08-03
      • 2021-01-13
      • 2019-05-27
      • 2020-08-12
      相关资源
      最近更新 更多