Django Rest Framework - get bound model field in serializer

I am trying to return an HttpResponse from the Django Rest Framework, including data from 2 related models. Models:

class Wine(models.Model): color = models.CharField(max_length=100, blank=True) country = models.CharField(max_length=100, blank=True) region = models.CharField(max_length=100, blank=True) appellation = models.CharField(max_length=100, blank=True) class Bottle(models.Model): wine = models.ForeignKey(Wine, null=False) user = models.ForeignKey(User, null=False, related_name='bottles') 

I would like to have a serializer for the Bottle model that includes information from the associated Wine.

I tried:

 class BottleSerializer(serializers.HyperlinkedModelSerializer): wine = serializers.RelatedField(source='wine') class Meta: model = Bottle fields = ('url', 'wine.color', 'wine.country', 'user', 'date_rated', 'rating', 'comment', 'get_more') 

which does not work.

Any ideas how I could do this?

Thank:)

+43
python django serialization django-rest-framework foreign-keys
Dec 17 '13 at 11:48
source share
2 answers

Just like that by adding WineSerializer as the field that it allowed.

 class BottleSerializer(serializers.HyperlinkedModelSerializer): wine = WineSerializer(source='wine') class Meta: model = Bottle fields = ('url', 'wine', 'user', 'date_rated', 'rating', 'comment', 'get_more') 

from:

 class WineSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Wine fields = ('id', 'url', 'color', 'country', 'region', 'appellation') 

Thanks for the help @mariodev :)

+52
Dec 17 '13 at 14:12
source share

If you want to get a specific field, you can use serializer fields

https://www.django-rest-framework.org/api-guide/fields/

  class BottleSerializer(serializers.HyperlinkedModelSerializer): winecolor = serializers.CharField(read_only=True, source="wine.color") class Meta: model = Bottle fields = ('url', 'winecolor', 'user', 'date_rated', 'rating', 'comment', 'get_more') 
0
Jan 31 '19 at 8:56
source share



All Articles