我有三种模式:
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会只返回实体,它会错过我entity_alert_relationship
使用EntityToAlertMap
部分的DistinctAlert
字段将实体映射到manytomany字段中的不同警报。我的问题是,如何在维护实体/关系字段时序列化In [77]: X_R
Out[77]:
dollars dollars
0 0.7085 0.5000
答案 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')