Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename ForeignKey set field in Django Rest Framework

I am serializing Foreign key set using Django Rest Framework, I have 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 them 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 back referenced _set queryset... But transaction_set just seems very awkward name in API for that..

like image 473
Visgean Skeloru Avatar asked Aug 30 '14 00:08

Visgean Skeloru


People also ask

How do you get a foreign key field name instead of ID in Django REST framework?

If you want to show any field of foreign key instead of id then you can use StringRelatedField.

How do you save a foreign key field in Django REST framework?

Your code is using serializer only for validation, but it is possible use it to insert or update new objects on database calling serializer. save() . To save foreign keys using django-rest-framework you must put a related field on serializer to deal with it. Use PrimaryKeyRelatedField .

What is Slug related field in Django?

SlugField in Django is like a CharField, where you can specify max_length attribute also. If max_length is not specified, Django will use a default length of 50. It also implies setting Field.

What is serializer method field in Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


1 Answers

After a quick experimenting I have discovered that this will 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 the statuses linked by foreign key with a nice name...

like image 194
Visgean Skeloru Avatar answered Sep 17 '22 10:09

Visgean Skeloru