Почему не удается получить связанные данные в Self-referencing many-to-many в Django?

Я новичок в django и работаю над небольшим приложением, содержащим модель nameCustomUser.CustomUser имеет отношения ManyToMany с самим собой, я реализовал функцию, что пользователь может следовать за другим пользователем. Но когда я пытаюсь получить всех пользователей, за которыми следует текущий аутентифицированный пользователь, я не получаю желаемого результата.

Модели:-

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))

view:-

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..

Заранее спасибо... Надеюсь получить от вас ответ в ближайшее время.

Вы получаете менеджер, а не кверисет, вам нужно использовать .all() [Django-doc] для получения QuerySet менеджера, которым управляет менеджер, так:

class CustomUser(AbstractUser):
    # ⋮

    def get_all_followings(self):
        print(f'print {self}')
        print(f'all followings {self.to_person.all()}')

В вашей модели вы можете указать отношение с помощью:

class CustomUser(AbstractUser):
    # ⋮
    following = models.ManyToManyField(
        'self',
        through='Relationship',
        through_fields=('from_person', 'to_person'),
        symmetrical=False,
        related_name='related_to'
    )

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name', 'username']

Тогда вы можете получить доступ к фолловерам с помощью:

current_user.following.all()
Вернуться на верх