DRF serializers how to best handle indirect references to a FK?

Viewed 34

Let's say I have the following models:

class Thing(models.Model):
    
    thing_key = models.AutoField(primary_key=True)
    state = models.ForeignKey(State, db_column='state_key', on_delete=models.CASCADE, default=0)
    [...other fields unrelated to the question...]

    class Meta:
        db_table = 'THING'

class State(models.Model):
    state_key = models.AutoField(primary_key=True)
    flag = models.IntegerField(unique=True)
    description = models.CharField(max_length=50)

    class Meta:
        db_table = 'STATE'

And let's say I need to create new Things based on data received via POST requests.

And let's say these POST requests do NOT contain the FK of Thing, which is state_key, but actually the flag field from the State model.

What is the best way to implement serializers that help accomplish the following things:

  1. Create a new Thing even though the state_key is unknown.
  2. Return a serialized representation of the newly created Thing without exposing the state_key.

After reading and re-reading the documentation, the best I could do is the following. It works, but I'm suspect there's a much more straightforward way to do it:

class FlagField(serializers.RelatedField):      
    def to_representation(self, value):          
        return value.flag     
    def to_internal_value(self, data):         
        return State.objects.get(flag=data)  

class ThingSerializer(serializers.ModelSerializer):      
    state_flag = FlagField(queryset=State.objects.all(), source='state')     
    class Meta:         
        model = Thing
        exclude = ['state']

Is this an acceptable approach? If not, what is wrong with it and how else could I accomplish the goal?

Thanks in advance!

0 Answers
Related