我有模特:
class Order(models.Model):
user = models.ForeignKey('accounts.User', blank=True, null=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
class Reservation(models.Model):
start = models.DateTimeField(db_index=True)
end = models.DateTimeField(db_index=True)
order = models.ForeignKey(Order, related_name='reservations')
和序列化器:
class ReservationSerializer(serializers.HyperlinkedModelSerializer):
order_first_name = serializers.CharField(read_only=True)
order_last_name = serializers.CharField(read_only=True)
order_id = serializers.IntegerField(read_only=True)
class Meta:
model = Reservation
fields = ('id',
'start',
'end',
'order',
'order_first_name',
'order_last_name',
'order_id',
)
read_only_fields = ('order', 'order_first_name', 'order_last_name', 'order_id')
问题是我在API响应中看不到order_first_name
和order_last_name
,也没有错误。
答案 0 :(得分:0)
好的,这可行
order_first_name = serializers.ReadOnlyField(source =' order.first_name',read_only = True)