帮我使用DRF框架写出一个根据用户填写的用户名称模糊查询用户的接口,接口返回字段为用户头像地址,用户名称,是否关注当前账号。
时间: 2024-02-20 15:59:52 浏览: 61
好的,下面是一个简单的实现:
首先,需要定义一个`User`模型,包含用户名称和头像地址等字段:
```python
from django.db import models
class User(models.Model):
name = models.CharField(max_length=50)
avatar = models.URLField()
# 其他字段...
```
然后,定义一个`UserSerializer`序列化器,将`User`模型转换为JSON格式:
```python
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
is_following = serializers.SerializerMethodField()
class Meta:
model = User
fields = ('name', 'avatar', 'is_following')
def get_is_following(self, obj):
# TODO: 判断当前账号是否关注了该用户
return False
```
接下来,定义一个`UserViewSet`视图集合,处理用户查询请求:
```python
from rest_framework import viewsets
from rest_framework.response import Response
from .models import User
from .serializers import UserSerializer
class UserViewSet(viewsets.ViewSet):
serializer_class = UserSerializer
def list(self, request):
name = request.query_params.get('name')
if not name:
return Response({'error': 'Missing parameter: name'}, status=400)
users = User.objects.filter(name__contains=name)
serializer = self.serializer_class(users, many=True, context={'request': request})
return Response(serializer.data)
```
最后,在`urls.py`中定义一个URL模式,将`UserViewSet`视图集合映射到`/api/users/`路径:
```python
from django.urls import path, include
from rest_framework import routers
from .views import UserViewSet
router = routers.DefaultRouter()
router.register(r'users', UserViewSet, basename='user')
urlpatterns = [
path('api/', include(router.urls)),
]
```
现在,当访问`/api/users/?name=xxx`时,就会返回所有名称包含`xxx`的用户的头像地址、名称和是否关注当前账号的信息。
阅读全文