简体   繁体   English

仅使用queryset方法时,DRF响应会返回所有字段

[英]DRF Response returning all fields when using queryset method only

I'm doing a university project that requires me to implement a Web App using an API as backend and I've decided to use DRF to do it but I'm having some troubles right now. 我正在做一个大学项目,要求我使用API​​作为后端来实现Web应用程序,但我决定使用DRF来实现它,但是现在遇到了一些麻烦。

I'm trying to override the list method in View to only show some fields when retrieving the list of all airports' records but still all fields are being returned in the Response. 我试图覆盖“视图”中的list方法,以在检索所有机场记录的列表时仅显示某些字段,但仍在“响应”中返回所有字段。

Model: 模型:

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

Serializer: 串行:

class AirportSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Airport
        fields = ('id', 'name', 'code', 'url', 'carriers')

View: 视图:

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)

Response: 响应:

{
        "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/"
        ]
    }

How can I solve this? 我该如何解决? Is there a better way to do it, I mean not using QuerySet.only method? 有没有更好的方法,我的意思是不使用QuerySet.only方法?

您应该定义一个单独的序列化器并返回它。

It is the serializer that defines how objects are serialized, not how you filter the data from the database. 序列化程序定义对象的序列化方式,而不是如何从数据库中过滤数据。 Currently, you have all fields available in the serializer. 当前,您在序列化程序中具有所有可用字段。 If you do not want some fields to be returned while listing or retrieving items, you can define those fields in the serializer as write_only , like this: 如果您不希望在列出或检索项目时返回某些字段,则可以在序列化程序中将这些字段定义为write_only ,如下所示:

class AirportSerializer(serializers.HyperlinkedModelSerializer):
    url = serializer.CharField(write_only=True)
    carriers = serializer.PrimaryKeyRelatedField(many=True, write_only=True)

    class Meta:
        model = models.Airport
        fields = ('id', 'name', 'code', 'url', 'carriers')

This way, url and carriers fields will not be present when data is returned, but will be required while inserting data. 这样,返回数据时url和carrier字段将不存在,但是在插入数据时将是必填字段。

just put the field which want in your serializer like that: 只需将想要的字段放在您的序列化器中,如下所示:

class AirportSerializer(serializers.HyperlinkedModelSerializer):
  class Meta:
     model = models.Airport
    fields = ('id', 'name', 'code')

You are good to go. 你已准备好出发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用 drf-yasg 指定 drf 查询集中的字段 - unable to specify the fields in drf queryset using drf-yasg 当Drf使用ListAPIView返回空查询集时如何返回404 - How to return a 404 when drf returns empty queryset using ListAPIView DRF 多字段基础匹配过滤器查询集 - DRF multi fields base match filter queryset 有没有办法在序列化数据之后只获取查询集中的特定字段,而不在 drf 中创建不同的序列化程序? - Is there a way to get only specific fields in a queryset after serialization data, without create a different serializer in drf? 仅限Django Queryset方法和外键实数字段('_id') - Django Queryset only method and foreign keys real fields ('_id') Django 序列化程序不返回所有字段作为响应 - Django serializer not returning all fields in response 如何使用 DRF 从 serializerMethodField 仅返回指定字段 - How to return only specified fields from serializerMethodField using DRF DRF 正则表达式搜索所有字段 - DRF regex search on all fields 在Django中进行内部联接查询集时获取所有字段 - Get all fields when making a innerjoin queryset in django 在序列化器字段中使用属性时如何优化 DRF 编号查询? - How to optimize DRF number queries when using properties in serializers fields?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM