Django - 如何正确访问反向关系 ManyToManyField

Django - How to properly access reverse relationship ManyToManyField

这是我的models.py(我也在使用默认的 Django 用户模型):

class UserExtended(models.Model):
    user = models.OneToOneField(User, related_name="userextended_set")
    location = models.ForeignKey(Location)
    follow = models.ManyToManyField(User, related_name="follow_set")

现在,要访问特定用户的 'follow' 用户列表(特定用户关注的用户),我会这样做:

a = User.objects.get(username='a')
a.userextended_set.follow.count()

我的问题是,如何获取特定用户在 'follow' 列表中的用户列表(即关注他的人)?我试过这个:

# Assuming user 'a' is on the 'follow' list of only one users (i.e.
# assuming .get() will only return one user object).
User.objects.get(username='a').follow_set.get().username

但我收到一条错误消息

AttributeError: 'UserExtended' object has no attribute 'username'

我认为这可能是您需要的:

user  # this is your user
UserExtended.objects.filter(follow=user)

请试试这个:

user_ids = UserExtended.objects.filter(follow__username='a') \
                               .values_list('user', flat=True).distinct()
result_users = User.objects.filter(id__in=user_ids)