【问题标题】:How to implement followers/following using ManyToManyField in Django?如何在 Django 中使用 ManyToManyField 实现关注者/关注?
【发布时间】:2020-03-03 18:28:11
【问题描述】:

我想在我的 Django 应用程序中使用 manytomanyfield 实现以下功能。 我为每个具有两个属性的用户创建了 UserProfile 类:用户和关注。用户继承默认的 Django 用户模型。

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name = 'user', on_delete=models.CASCADE)
    follows = models.ManyToManyField("self", related_name = 'follower',symmetrical=False )

我在 python shell 中试过这个:

>>> lily = User(username="Lily")
>>> lily.save()
>>> mary = User(username="Mary")
>>> mary.save()
>>> lily_profile = UserProfile(user=lily)
>>> lily_profile.save()
>>> mary_profile = UserProfile(user=mary)
>>> mary_profile.save()
>>> lily_profile.follows.add(mary_profile)

但是我在lily_profile.follows.add(mary_profile) 之后得到了这个错误:

django.db.utils.OperationalError: table polls_userprofile_follows has no column named from_userprofile_id

有谁知道如何解决这个错误?非常感谢!

【问题讨论】:

  • 您好,我不希望“self”为follows工作,而是为“UserProfile”工作。
  • UserProfile 是一个类。你不能在类中使用类名

标签: python sql django manytomanyfield twitter-follow


【解决方案1】:

尝试删除您的迁移文件,然后重新运行以下命令

python manage.py makemigrations 
python manage.py migrate 

【讨论】:

  • 总是快乐编码:)
  • 如果这个答案对你有帮助,那么请点赞并接受它,这样如果其他人遇到同样的问题并访问这个问题,他们会从这里找到值得信赖的答案。谢谢:)
猜你喜欢
  • 2018-12-10
  • 1970-01-01
  • 2023-01-17
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多