简体   繁体   English

使用Django Rest Framework根据各个字段值序列化查询集

[英]Serialize queryset based on individual field values using Django Rest Framework

Goal 目标

If an object has revealed=true it serializes into: 如果对象revealed=true它将序列化为:

{
   "id":1,
   "info":"top secret info",
   "revealed":true
}

If an object has revealed=false the info field is null : 如果对象revealed=falseinfo字段为null

{
   "id":2,
   "info":null,
   "revealed":false
}

So for a queryset of objects: 因此,对于对象的查询集:

[  
   {  
      "id":1,
      "info":"top secret info 1",
      "revealed":true
   },
   {
       "id":2,
       "info":null,
       "revealed":false
   },
   {  
      "id":3,
      "info":"top secret info 3",
      "revealed":true
   }
]

Is it possible to achieve this inside of a Django Rest Framework Model Serializer class? 是否可以在Django Rest Framework Model Serializer类内部实现此目的?

class InfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Info
        fields = ('id', 'info', 'revealed')

Background 背景

The DRF docs discuss some advanced serializer usage, and this other post dives into an example. DRF文档讨论了一些高级的序列化程序用法,而本文的后半部分将深入探讨一个示例。 However it doesn't seem to cover this particular issue. 但是,它似乎并未涵盖此特定问题。

Ideas 主意

A hacky solution would be to iterate over the serialized data afterwards, and remove the info field for every object that has revealed=false . 一个有问题的解决方案是在之后迭代序列化的数据,并为每个已revealed=false对象删除info字段。 However 1) it involves an extra loop and 2) would need to be implemented everywhere the data is serialized. 但是1)它涉及一个额外的循环,并且2)需要在数据序列化的任何地方实现。

I suggest you make the info field appear on all records, but leave it null when revealed is false. 我建议您使info字段出现在所有记录中,但是如果revealed为false,则将其保留为空。 If that's acceptable, you should be able to make it happen with a SerializerMethodField . 如果可以接受,则应该可以使用SerializerMethodField实现它。

Alternatively, you could add a revealed_info attribute to the model class, and expose that through the serializer. 另外,您可以向模型类中添加一个revealed_info属性,然后通过序列化器将其公开。

@property
def revealed_info(self):
    return self.info if self.revealed else None

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM