我想在django 1.8(使用django rest框架)中构建我的应用程序的api部分,我想通过ForeignKey访问另一个模型中的字段,但是我收到错误。
我的代码(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')
我收到类型错误:'Room' object is not iterable
答案 0 :(得分:3)
使用序列化程序,您可以访问外键引用的另一个字段:
class BoxSerializer(serializers.ModelSerializer):
field_in_room = serializers.ReadOnlyField(source='room.field_in_room')
class Meta:
model = Event
...