代码之家  ›  专栏  ›  技术社区  ›  ThunderHorn

Django ManyToOne序列化器中的关系获取正在调用的对象

  •  0
  • ThunderHorn  · 技术社区  · 4 年前

    `你好我的代码

    class MyRelatedModel(models.Model):
          related_model_instance = models.ForeignKey(MyModel........)
    
    class MyModel(models.Model)
          [....]
    

    串行器

    class MyRelatedModelSerialzier(serializers.ModelSerializer):
        related_models_instance = MyModelSerializer()
        class Meta:
           model = MyRelatedModel
           fields = ['id', 'name', 'related_model_instance']
    
    class MyModelSerailzier(serializer.ModelSerializer):
        parent_id = serializer.SerializerMethodfield('get_parent_id')
        def get_parent_id():
           # How to get the id of the object which is being serialized?
           # In order to make some calculations
           return 'foo' 
        class Meta:
           model = MyModel
           fields = ['id', 'name', 'parent_id',....
    

    提问

    我有两个模型,一对多

    在MyModelSerializer中,我需要知道哪个对象在调用,因为我需要它在返回响应之前计算一些值。我想重写MyRelatedSerialer的_representation,但它不适用于drf-yasg。。。

    1 回复  |  直到 4 年前
        1
  •  1
  •   Aayush Agrawal    4 年前
    class MyRelatedModelSerialzier(serializers.ModelSerializer):
        related_models_instance = MyModelSerializer(MyRelatedModel)
        class Meta:
           model = MyRelatedModel
           fields = ['id', 'name', 'related_model_instance']
    
    class MyModelSerailzier(serializer.ModelSerializer):
        parent_id = serializer.SerializerMethodfield('get_parent_id')
        def __init__(self, ParentModel):
            self.parent = ParentModel
        def get_parent_id():
           # How to get the id of the object which is being serialized?
           # In order to make some calculations
           return self.parent 
        class Meta:
           model = MyModel
           fields = ['id', 'name', 'parent_id',....
    

    这将在序列化过程中用父模型类初始化您的子模型