我有以下型号:
class FlightSchedule(models.Model):
tail_number = models.ForeignKey(TailNumber, null=False)
flight_number = models.CharField(max_length=30, null=False)
flight_group_code = models.ForeignKey(FlightGroup, null=False)
origin_port_code = models.ForeignKey(Port, null=False, related_name="Origin")
destination_port_code = models.ForeignKey(Port, null=False, related_name="Destination")
flight_departure_time = models.TimeField()
start_date = models.DateField()
end_date = models.DateField()
def __unicode__(self):
return u'%s' % self.flight_number
class Meta:
verbose_name_plural = "Flight Schedule"
class FlightScheduleDetail(models.Model):
flight_date = models.CharField(max_length=30, null=False)
flight_number = models.ForeignKey(FlightSchedule, null=False, related_name="flight_number_schedule")
route_id = models.CharField(max_length=30, null=False, unique=True)
flight_status = models.ForeignKey(Status, null=True, default=1)
def __unicode__(self):
return u'%s' % self.route_id
class Meta:
verbose_name_plural = "Flight Schedule Details"
,序列化器如下:
class FlightScheduleDetailSerializer(serializers.ModelSerializer):
class Meta:
model = FlightScheduleDetail
fields = '__all__'
class FlightScheduleSerializer(serializers.ModelSerializer):
flight_number_schedule = FlightScheduleDetailSerializer(many=True)
class Meta:
model = FlightSchedule
fields = ['tail_number', 'flight_number', 'origin_port_code', 'destination_port_code', 'flight_departure_time',
'flight_number_schedule']
这里tail_number,flight_number是外键。当我创建API时,我将响应作为字段的id。如何在json中显示名称?
我的views.py如下:
@api_view(['GET'])
def flight_schedule(request):
schedule = FlightSchedule.objects.all()
serializer = FlightScheduleSerializer(schedule, many=True)
return Response(serializer.data)
答案 0 :(得分:2)
您可以在序列化程序中使用field_name定义源,如下所示。
我使用过source='TailNumber.number'
。请使用正确的field_name代替number
class UserProfileSerializer(serializers.ModelSerializer):
tail_number = serializers.CharField(source='TailNumber.number', read_only=True)
flight_number = ....(change as above)
class Meta:
model = FlightSchedule
fields = ['tail_number', 'flight_number', 'origin_port_code', 'destination_port_code', 'flight_departure_time',
'flight_number_schedule']
答案 1 :(得分:1)
您可以简单地将它们添加为属性。
flight_number_str = serializers.ReadOnlyField(source='flight_number.flight_number')
首先flight_number
是FlightScheduleDetail
的属性,然后是FlightSchedule
然后将其添加到字段列表fields = [..., 'flight_number_str']
否则,您可以查看DRF中的nested relationships,它也可以提供更多可能性。
答案 2 :(得分:0)
另一种方法是在序列化程序中使用depth
选项。它是指定嵌套序列化 - doc
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
depth = 1
如果用户是外键或许多键,则序列化程序会将用户显示为对象而不是键。
depth
选项应设置为指示的整数值 在恢复之前应该遍历的关系深度 平面代表。