简体   繁体   English

字段序列化器 Django

[英]Field Serializers Django

I have a serializer with some custom fields and those fields depends on a specific query.我有一个带有一些自定义字段的序列化程序,这些字段取决于特定查询。 The problem is that each time the serializer tries to get the value for this field It must perform the query to the DB.问题在于,每次序列化程序尝试获取该字段的值时,它都必须对 DB 执行查询。 What about if the serializer is a many=True serializer?.如果序列化器是 many=True 序列化器呢?

class ExampleSerializer(serializers.ModelSerializer):

  field_one = serializers.SerializerMethodField()
  field_two = serializers.SerializerMethodField()
  field_three = serializers.SerializerMethodField()
  .
  .
  .

  def get_field_one(self, obj):
    try:
      # This is where i do the query
      query_result = obj.objects.filter(filter=self.context.get("filter").first()
      if query_result:
        # Do field one stuff
    except Exception:
      # Do exception stuff

  def get_field_two(self, obj):
    try:
     # This is where i do the query
     query_result = obj.objects.filter(filter=self.context.get("filter").first()
     if query_result:
        # Do field two stuff
    except Exception:
      # Do exception stuff

  def get_field_three(self, obj):
    try:
     # This is where i do the query
     query_result = obj.objects.filter(filter=self.context.get("filter").first()
     if query_result:
        # Do field three stuff
    except Exception:
      # Do exception stuff

Is there a way to store that result inside a property in the serializer?有没有办法将该结果存储在序列化程序的属性中? Also, if I set a value in one of the serializer field, how do I retrieve and do some maths on another field in the same serializer?另外,如果我在序列化程序字段之一中设置了一个值,我如何在同一个序列化程序中的另一个字段上检索和执行一些数学运算?

If I have a choice, I would do all these calculation logic in a single method如果我有选择,我会在一个方法中完成所有这些计算逻辑

class ExampleSerializer(serializers.ModelSerializer):
    generic_field = serializers.SerializerMethodField()

    def get_generic_field(self, obj):
        # first query
        first_result = FirstModel.objects.filter(
            filter=self.context.get("filter")
        ).aggrgate(sum=Sum('any_field'))['sum']
        # second query
        second_model_instance = SecondModel.objects.filter(
            some_value__gte=first_result).first()

        second_result = second_model_instance.some_field_name

        # and so on

        # at last, return these results as
        return {
            "first_result": first_result,
            "second_result": second_result,
            # and so on
        }

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

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