【发布时间】:2019-08-05 05:42:08
【问题描述】:
我正在做一个大学项目,需要我使用 API 作为后端来实现一个 Web 应用程序,我决定使用 DRF 来完成它,但我现在遇到了一些麻烦。
我正在尝试覆盖 View 中的 list 方法,以便在检索所有机场记录的列表时仅显示一些字段,但在响应中仍然返回所有字段。
型号:
class Airport(models.Model):
code = models.CharField(max_length=10)
name = models.TextField()
carriers = models.ManyToManyField(Carrier, related_name='airports')
def __str__(self):
return self.name
序列化器:
class AirportSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Airport
fields = ('id', 'name', 'code', 'url', 'carriers')
查看:
class AirportView(viewsets.ModelViewSet):
queryset = models.Airport.objects.all()
serializer_class = AirportSerializer
def list(self, request):
airports = models.Airport.objects.only('id', 'name', 'code')
data = AirportSerializer(airports, many=True, context={'request': request}).data
return Response(data)
回复:
{
"id": 4,
"name": "Leo",
"code": "Test",
"url": "http://localhost:8000/api/airports/4/",
"carriers": []
},
{
"id": 5,
"name": "asdasd",
"code": "aasdasd",
"url": "http://localhost:8000/api/airports/5/",
"carriers": [
"http://localhost:8000/api/carriers/1/"
]
},
{
"id": 6,
"name": "asdasd",
"code": "aasdasd",
"url": "http://localhost:8000/api/airports/6/",
"carriers": [
"http://localhost:8000/api/carriers/1/"
]
}
我该如何解决这个问题? 有没有更好的方法,我的意思是不使用 QuerySet.only 方法?
【问题讨论】:
-
你可以从这个帖子stackoverflow.com/questions/27935558/…得到一些帮助
标签: django python-3.x django-rest-framework django-views django-serializer