How to rename ForeignKey input field in Django Rest Framework

I am serializing an external key set using the Django Rest Framework, I have the following models:

class Transaction(models.Model): ... class TransactionStatus(models.Model): transaction = models.ForeignKey(Transaction) ... 

I have a serializer for both of these models, one of which looks like this:

 class TransactionSerializer(serializers.ModelSerializer): transactionstatus_set = TransactionStatusSerializer(many=True, read_only=True) class Meta: model = Transaction depth = 1 fields = ('id', 'transactionstatus_set') 

I want to have here a list of transaction statuses from backsetsetsetsetsetsetsetsetsetsetset ... But transaction_set just seems like a very inconvenient name in the API for this.

+5
source share
1 answer

After a quick experiment, I found that this would do the trick:

 class TransactionSerializer(serializers.ModelSerializer): changes = TransactionStatusSerializer(many=True, read_only=True, source='transactionstatus_set') class Meta: model = Transaction depth = 1 fields = ('id', 'changes') 

Now I have a list of statuses associated with a foreign key with a good name ...

+9
source

Source: https://habr.com/ru/post/1201455/


All Articles