我是 django 的新手,正在开发一个包含模型名称CustomUser.CustomUser 的小型应用程序,它与自身具有多对多关系,我已经实现了用户可以关注另一个用户的功能。但是当我试图获取当前经过身份验证的所有用户时跟随我没有得到想要的结果。
楷模:-
class CustomUser(AbstractUser):
email = models.EmailField(max_length=250, null=False, unique=True)
name = models.CharField(max_length=50, null=False)
username = models.CharField(max_length=50, null=False)
password = models.CharField(max_length=15, null=False)
user = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to')
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name', 'username']
def get_all_followings(self):
print("print {}".format(self))
print("all followings {}".format(self.to_person))
class Relationship(models.Model):
from_person = models.ForeignKey(CustomUser, related_name='from_people', on_delete=models.CASCADE)
to_person = models.ForeignKey(CustomUser, related_name='to_person', on_delete=models.CASCADE)
from_person表示正在关注的人,而to_person表示他正在关注的人。例如,在我的情况下deep是当前经过身份验证的用户,并且他正在关注ram。
因此,如果我尝试打印关系对象,则会得到以下输出:
{'_state': <django.db.models.base.ModelState object at 0x00000273836034C0>, 'id': 1, 'from_person_id': 2, 'to_person_id': 4}
看法:-
def see_all_followings(request):
if request.method == 'GET':
current_user = CustomUser.objects.get(id=request.user.id)
all_followings = current_user.get_all_followings()
# return render(request, "all_followings.html", {'users':, 'is_follow': True})
我得到的输出:-
Quit the server with CTRL-BREAK.
print deep@gmail.com
all followings user.Relationship.None # But user is following one user..
在此先感谢..希望您尽快来这里..