Django序列化模型与自定义多对多映射

时间:2016-11-23 21:56:54

标签: python django django-rest-framework

我有三种模式:

class DistinctAlert(models.Model):
    entities = models.ManyToManyField(to='Entity', db_index=True, through='EntityToAlertMap')

class Entity(models.Model):
    entity_instance = models.ManyToManyField(EntityInstance)

class EntityToAlertMap(models.Model):
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE)
    distinct_alert = models.ForeignKey(DistinctAlert, on_delete=models.CASCADE)
    entity_alert_relationship_label = models.ForeignKey(EntityAlertRelationshipLabel, on_delete=models.CASCADE,
                                                        null=True)

忽略额外字段DistinctAlertEntity,这就是我的序列化工具的样子:

class EntitySerializer(serializers.ModelSerializer):
    entity_instance = EntityInstanceSerializer(many=True)

    class Meta:
        model = Entity
        fields = ('id', 'entity_instance')

class EntityInstanceSerializer(serializers.ModelSerializer):
    entity_type = EntityTypeSerializer()

    class Meta:
        model = EntityInstance
        fields = ('label', 'entity_type')

class DistinctAlertSerializer(serializers.ModelSerializer):
    entities = EntitySerializer(many=True)

    class Meta:
        model = DistinctAlert
        #TODO how do I serialize custom mapping?
        fields = ('id', 'entities')

我的问题是,有了这个,我的api会只返回实体,它会错过我entity_alert_relationship使用EntityToAlertMap部分的DistinctAlert字段将实体映射到manytomany字段中的不同警报。我的问题是,如何在维护实体/关系字段时序列化In [77]: X_R Out[77]: dollars dollars 0 0.7085 0.5000

1 个答案:

答案 0 :(得分:2)

您可以为EntityToAlertMap

编写序列化程序
class EntityToAlertMap(serializers.ModelSerializer):
    class Meta:
        model = EntityToAlertMap
        fields = ('entity', 'distinct_alert', 'entity_alert_relationship_label')

然后通过相关管理器

检索所有相关的EntityToAlertMap实例
class DistinctAlertSerializer(serializers.ModelSerializer):
    entities = EntitySerializer(many=True)
    entity_to_alert_map = EntityToAlertMap(source='entitytoalertmap_set', many=True)

    class Meta:
        model = DistinctAlert
        fields = ('id', 'entities', 'entity_to_alert_map')