这是我的模型.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")
现在,为了访问特定用户的"关注"用户列表(特定用户正在关注的用户),我会做如下操作:
a = User.objects.get(username='a')
a.userextended_set.follow.count()
我的问题是,如何获得特定用户在"关注"列表中的用户列表(即关注他的用户)?我试过这个:
# 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)