如何获取与django rest框架中的外键相关的数据?
How to get data related to a foreign key in django rest framework?
我要为一个事件创建一个约会,我的模型如下-
event/models.py
class Event(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
event_name = models.CharField(max_length=200)
event_location = models.CharField(max_length=200, default='')
appointment/models.py
class Appointment(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
event = models.ForeignKey(Event, on_delete=models.CASCADE)
appointment_date = models.DateTimeField(default=datetime.datetime.now)
而约会序列化程序是 -
appointment/serializers.py
class AppointmentSerializer(serializers.ModelSerializer):
class Meta:
model = Appointment
fields = ('id', 'event', 'appointment_date')
我可以按如下方式创建约会 -
POST appointment
request params -
event:6625dc74-dc36-4a22-9fac-c63e96fe6049
appointment_date:2017-06-26 18:30:00
response
{
"id": "08c975bc-c4d8-4e90-a4b2-bdb2cd69e9e8",
"event": "6625dc74-dc36-4a22-9fac-c63e96fe6049",
"appointment_date": "2017-06-26 18:30:00"
}
但我需要事件作为事件对象,而不是事件 ID 字符串,例如 -
[
"id": "08c975bc-c4d8-4e90-a4b2-bdb2cd69e9e8",
"event": {
"id": "6625dc74-dc36-4a22-9fac-c63e96fe6049",
"event_name": "Test Event",
"event_location": "TVM, IND"
},
"appointment_date": "2017-06-26 18:30:00"
]
在你的序列化器中 class 定义 depth=1
因此您的序列化器将是:
class AppointmentSerializer(serializers.ModelSerializer):
class Meta:
model = Appointment
fields = ('id', 'event', 'appointment_date')
depth = 1
我要为一个事件创建一个约会,我的模型如下-
event/models.py
class Event(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
event_name = models.CharField(max_length=200)
event_location = models.CharField(max_length=200, default='')
appointment/models.py
class Appointment(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
event = models.ForeignKey(Event, on_delete=models.CASCADE)
appointment_date = models.DateTimeField(default=datetime.datetime.now)
而约会序列化程序是 -
appointment/serializers.py
class AppointmentSerializer(serializers.ModelSerializer):
class Meta:
model = Appointment
fields = ('id', 'event', 'appointment_date')
我可以按如下方式创建约会 -
POST appointment
request params -
event:6625dc74-dc36-4a22-9fac-c63e96fe6049
appointment_date:2017-06-26 18:30:00
response
{
"id": "08c975bc-c4d8-4e90-a4b2-bdb2cd69e9e8",
"event": "6625dc74-dc36-4a22-9fac-c63e96fe6049",
"appointment_date": "2017-06-26 18:30:00"
}
但我需要事件作为事件对象,而不是事件 ID 字符串,例如 -
[
"id": "08c975bc-c4d8-4e90-a4b2-bdb2cd69e9e8",
"event": {
"id": "6625dc74-dc36-4a22-9fac-c63e96fe6049",
"event_name": "Test Event",
"event_location": "TVM, IND"
},
"appointment_date": "2017-06-26 18:30:00"
]
在你的序列化器中 class 定义 depth=1
因此您的序列化器将是:
class AppointmentSerializer(serializers.ModelSerializer):
class Meta:
model = Appointment
fields = ('id', 'event', 'appointment_date')
depth = 1