I have two models to expose via an API: every RegionValue has a ForeignKey to a MapAnswer. I wish to represent this in our API built using rest_framework by making the RegionValues a field inside the MapAnswer endpoint. My rest_framework serializers looks like this:
class RegionValueSerializer(serializers.ModelSerializer):
class Meta:
model = RegionValue
fields = ('region_id', 'value')
class MapAnswerSerializer(serializers.ModelSerializer):
regionvalue_set = RegionValueSerializer(many=True, allow_add_remove=True, required=False)
declined = serializers.BooleanField(required=False)
class Meta:
model = MapAnswer
fields = ('declined', 'regionvalue_set')
This works fine from a read perspective, but updating the regionvalue_set has an issue where new RegionValues are always created instead of linking to an existing RegionValue. If I include 'id' in the fields of RegionValueSerializer then it solves this problem, but I'd prefer not to expose the primary key! The RegionValues are uniquely determined by the their region_id and the MapAnswer they are associated with.