如何通过用户关系表中的外键获取 User 的实例?
不好意思,我这应该算是提了一个 xy问题
我的需求是想通过
rest framework
的
@detail_route
修饰符实现类似
/users/{user_id}/fans/
这种风格的路由,但是在写方法的时候不知道除了循环提取还有什么办法获取
user
列表,后来这样写了,可以用,但是不知道是不是真的好
class UserViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list` and `detail` actions.
"""
queryset = MyUser.objects.all()
serializer_class = UserSerializer
filter_class = UserFilter
@detail_route(methods=['get'], url_path='fans')
def get_fans(self, request, pk=None):
instance = self.get_object()
from_user_list = []
follows = instance.fans.filter(followed=True)
# 这里通过调用 rest framework 的分页方法进行分页操作
# 然后提取出指定数量的实例再进行提取
page = self.paginate_queryset(follows)
for f in page:
from_user_list.append(f.from_user)
serializer = self.get_serializer(from_user_list, many=True)
return self.paginator.get_paginated_response(serializer.data)
下面的问题提问的并不好
用户关系表为
class Follow(models.Model):
from_user = models.ForeignKey('User', related_name='followers')
to_user = models.ForeignKey('User', related_name='fans')
此时有一个 User 实例,我想通过 fans 获取它的所有粉丝
u = User.objects.get(id=1)
u.fans.all()
此时获取到了一个 Follow 列表 [< Follow: >, < Follow: >]
请问如何才能获取到 User 列表?
python django django-rest-framework
Answers
https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.mod...
ForeignKey.related_query_name The name to use for the reverse filter
name from the target model. Defaults to the value of related_name if
it is set, otherwise it defaults to the name of the model:
# Declare the ForeignKey with related_query_name
class Tag(models.Model):
article = models.ForeignKey(Article, related_name="tags", related_query_name="tag")
name = models.CharField(max_length=255)
# That's now the name of the reverse filter
Article.objects.filter(tag__name="important")