Retrieving a Foreign Key Value with Django-Rest-Framework Serializers

Retrieving a Foreign Key value with django-rest-framework serializers

Just use a related field without setting many=True.

Note that also because you want the output named category_name, but the actual field is category, you need to use the source argument on the serializer field.

The following should give you the output you need...

class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.RelatedField(source='category', read_only=True)

class Meta:
model = Item
fields = ('id', 'name', 'category_name')

Django Rest Framework, How do I grab a foreign key value and add it to my serializer or view to create a new object?

Assuming the profile is for the currently logged in user, you can do something like this in your save():

serializer.save(username_id=request.user)

This will set username_id foreign key to the currently logged in user.

How to serialize the foreign key field in django rest framework

You can make use of to_representation()

Give this a try

class CartSerializer(serializers.ModelSerializer):

class Meta:
model = Cart

def to_representation(self, instance):
representation = dict()
representation["id"] = instance.id
representation["user"] = instance.user.username
representation["item"] = instance.item.name
representation["quantity"] = instance.quantity
representation["created_at"] = instance.created_at
representation["updated_at"] = instance.updated_at

return representation

NB: You may have to change instance.field_name(s) accordingly

Get Value of Foreign Key in Django-rest Serializer

You have a mistake in specifying the source. Change it to source="document_type.title" because you want to say "use the title of the document_type field of this instance":

class DocumentCountsSerializer(serializers.ModelSerializer):
title = serializers.CharField(source="document_type.title", read_only=True)

class Meta:
model = DocumentsCount
fields = "__all__"

You were having a problem because there's no field DocumentType defined on the DocumentsCount model (the field is document_type which is a foreign key to DocumentType).

Serializing/deserializing a foreign key in django rest framework

SlugRelatedField is what you're looking for. This is both read and write.

class ItemSerializer(serializers.ModelSerializer):
category = serializers.SlugRelatedField(
slug_field='name',
queryset=Category.objects.all()
)

class Meta:
model = Item
fields = ('id', 'name', 'category')

Precision: you need to make your category.name unique=True in your models.py.

How to retrieve foreign key field in Django rest framework?

I think you need custom field, try this serializer:

class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ('title', 'artist','artist_name')

artist_name = serializers.SerializerMethodField('get_artists_name')

def get_artists_name(self, obj):
return obj.artist.name

It produce something like this.

[
{
"title": "Don't let me down",
"artist": 2,
"artist_name": "The Beatles"
},
{
"title": "Summertime",
"artist": 1,
"artist_name": "Ella Fitzgerald"
}
]

Get fields of foreign key in serializer django

I did it like this and it worked like a charm. Hope the answer helps a newbie in the future!

class StudentSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField()
firstname = serializers.CharField(source='user.firstname')
lastname = serializers.CharField(source='user.lastname')

class Meta:
model = Student
fields = ('firstname', 'lastname', 'id', 'school', 'field_of_study')


Related Topics



Leave a reply



Submit