我目前正在嘗試在用戶之間創(chuàng)建以下關(guān)系,因此我在用戶模型中使用了多對多字段來引用自身。class User(AbstractUser): followers = models.ManyToManyField('self', related_name='following') def __str__(self): return self.username但是,當(dāng)我使用 shell 測試此模型并嘗試訪問 related_name 時,它報告發(fā)生了錯誤。>>> u1 = User.objects.get(pk=1)>>> u1.following.all()Traceback (most recent call last): File "<console>", line 1, in <module>AttributeError: 'User' object has no attribute 'following'現(xiàn)在我真的很困惑,真的需要幫助或其他方法來做到這一點。
3 回答

絕地?zé)o雙
TA貢獻(xiàn)1946條經(jīng)驗 獲得超4個贊
它應(yīng)該看起來像這樣
class User(AbstractUser):
? ? followers = models.ManyToManyField(
? ? ? ? 'self',
? ? ? ? symmetrical=False,
? ? ? ? related_name='following',
? ? )

慕絲7291255
TA貢獻(xiàn)1859條經(jīng)驗 獲得超6個贊
我認(rèn)為 Django 不允許我們在字段引用自身時給出 related_name 。
他們本質(zhì)上做的是創(chuàng)建另一個名為 Following() 的模型,并用它來存儲關(guān)系。
class?Following(models.Model): ????target?=?models.ForeignKey('User',?on_delete=models.CASCADE,?related_name?=?"followers") ????follower?=?models.ForeignKey('User',?on_delete=models.CASCADE,?related_name?=?"targets")

慕姐4208626
TA貢獻(xiàn)1852條經(jīng)驗 獲得超7個贊
如果將多對多關(guān)系指定給其他模型,則 related_name 屬性指定從用戶模型返回到您的模型的反向關(guān)系的名稱。
但在這種情況下......兩個模型是相同的
所以你試試這個
u1 = User.objects.get(pk=1) u1.followers.all()
添加回答
舉報
0/150
提交
取消