git-e
git-e

Reputation: 299

Access to field in another model via ForeignKey in django rest

I want to build api part of my app in django 1.8 (with django rest framework) and I want to get access to field in another model via ForeignKey but I get an error.

My code (models.py):

class Event(models.Model):
...
is_date_end_confirmed = models.BooleanField(default=True)
room = models.ForeignKey('events.Room', related_name='bookings')
room_description = models.CharField(max_length=255)
...

serializers.py

class BoxSerializer(serializers.ModelSerializer):
    room = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Evnet
        fields = ('id', 'date_start', 'room')

And I get Type error: 'Room' object is not iterable

Upvotes: 2

Views: 1381

Answers (1)

Evans Murithi
Evans Murithi

Reputation: 3257

Using serializers you can have access to another field referenced by a Foreign Key by doing:

class BoxSerializer(serializers.ModelSerializer):
    field_in_room = serializers.ReadOnlyField(source='room.field_in_room')

    class Meta:
        model = Event
        ...

Upvotes: 5

Related Questions