我有三个模型:
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)
除了DistinctAlert
和Entity
两个额外字段外,我的序列化程序如下:
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,它只会返回实体,并且错过了在我用于将实体映射到ManyToMany字段中的不同警报的EntityToAlertMap的“entity_alert_relationship”字段。我的问题是,如何序列化DistinctAlert同时保持实体/关系字段。