我正在从一个基于类的视图followtogleapiview向另一个userdetailapieview传递(is\u followed)参数。我使用Django会话(从这个平台上读取其他线程)来实现这一点,希望在UserSingleProfileSerializer上显示user\u to\u toggle变量的follow status(True或False)。你知道吗
以下是我的观点:
class UserDetailAPIVIew(generics.RetrieveAPIView):
'''
Displays a list of a user's posts
'''
serializer_class = UserSingleProfileSerializer
queryset = User.objects.all()
def get_object(self):
self.object = get_object_or_404(User,
username__iexact=self.kwargs.get('username')
)
return self.object
def get_serializer_context(self):
'''
passing the extra is_following argument to the UserDetailAPIVIew
'''
context = super(UserDetailAPIVIew, self).get_serializer_context()
is_followed = self.request.session.get('followed')
context.update({'followed': is_followed})
return context
class FollowToggleAPIView(APIView):
'''
Uses the custom model manager for user toggle follow
'''
def get(self, request, username, format=None):
user_to_toggle = get_object_or_404(User, username__iexact=username)
me = request.user
message = 'Not allowed'
if request.user.is_authenticated():
is_followed = UserProfile.objects.toggle_follow(me, user_to_toggle)
request.session['followed'] = is_followed
return Response({'followed': is_followed})
return Response({'message': message}, status=400)
toggle\u follow方法在自定义模型管理器中定义如下:
class UserProfileManager(models.Manager):
def toggle_follow(self, user, to_toggle_user):
''' follow unfollow users '''
user_profile, created = UserProfile.objects.get_or_create(user=user)
if to_toggle_user in user_profile.following.all():
user_profile.following.remove(to_toggle_user)
added = False
else:
user_profile.following.add(to_toggle_user)
added = True
return added
class UserProfile(models.Model):
'''
Extends the Django User model
'''
user = models.OneToOneField(settings.AUTH_USER_MODEL,
related_name='profile')
following = models.ManyToManyField(settings.AUTH_USER_MODEL,
blank=True,
related_name='followed_by')
objects = UserProfileManager()
def get_absolute_url(self):
return reverse_lazy('profiles:detail',
kwargs={'username':self.user.username})
def __str__(self):
return 'Username: {} [ Followers ({});
Following({})]'.format(self.user.username,
self.user.followed_by.all().count(),
self.following.all().count())
那个网址.py地址:
urlpatterns = [
url(r'^(?P<username>[\w.@+-]+)/$', UserDetailAPIVIew.as_view(),
name='user-posts-api'),
url(r'^(?P<username>[\w.@+-]+)/follow/$',
FollowToggleAPIView.as_view(), name='follow-api'),
]
唯一的问题是,UserSingleProfileSerializer中显示的(后面跟着)值一次为所有用户实例设置(而不是为我们要跟随的特定用户设置)。你知道吗
我当然不会同时跟踪/取消跟踪所有用户(因为followtogleapiview通过用户名针对特定用户)。你知道吗
我想知道如何将(的值只传递给userdetailapieview中的特定用户(user-to-toggle)。先谢谢你。你知道吗
在这里使用会话是完全错误的。您正在存储一个“followed”值,该值只记录他们切换的最后一个用户,与他们实际查看的配置文件没有关系。你知道吗
与其这样做,您只需在userdetailapieview中查询特定用户的后续状态。你知道吗
另外请注意,toggle方法本身效率很低—不需要从数据库中检索每个follow来检查当前用户是否在其中。再次使用
exists
:相关问题 更多 >
编程相关推荐