3

I have three models:

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)

Disregarding the extra fields DistinctAlert and Entity has, this is what my serializer looks like:

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')

My problem is, with this, my api will return me just the entity, and it misses out the entity_alert_relationship field that's part of the EntityToAlertMap that I'm using to map entities to distinct alerts in a manytomany field. My question is, how can I serialize the DistinctAlert while maintaining the entity/relationship field

Ivan Semochkin
  • 8,649
  • 3
  • 43
  • 75
Stupid.Fat.Cat
  • 10,755
  • 23
  • 83
  • 144
  • 2
    Have a look at this question: http://stackoverflow.com/questions/17256724/include-intermediary-through-model-in-responses-in-django-rest-framework. The accepted answer is what you are looking for. – AKS Dec 08 '16 at 06:26
  • Did the post in the above comment not help you find an answer? – AKS Dec 10 '16 at 13:27

1 Answers1

2

You could write serializer for EntityToAlertMap

class EntityToAlertMap(serializers.ModelSerializer):
    class Meta:
        model = EntityToAlertMap
        fields = ('entity', 'distinct_alert', 'entity_alert_relationship_label')

Then you retrieve all related EntityToAlertMap instances via related manager

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')
Ivan Semochkin
  • 8,649
  • 3
  • 43
  • 75