如何在django rest框架中获取与外键相关的数据?

Sij*_*A S 1 django django-models django-serializer django-rest-framework

我必须为一个事件创建一个约会,我的模型如下 -

事件/模型.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='')
Run Code Online (Sandbox Code Playgroud)

约会/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)
Run Code Online (Sandbox Code Playgroud)

约会序列化程序是-

约会/serializers.py

class AppointmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Appointment
        fields = ('id', 'event', 'appointment_date')
Run Code Online (Sandbox Code Playgroud)

我可以按如下方式创建约会 -

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"
    }
Run Code Online (Sandbox Code Playgroud)

但我需要事件作为事件对象,而不是事件 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"
]
Run Code Online (Sandbox Code Playgroud)

Aji*_*mes 5

在你的序列化器类中定义 depth=1

所以你的序列化器将是:

class AppointmentSerializer(serializers.ModelSerializer):
class Meta:
    model = Appointment
    fields = ('id', 'event', 'appointment_date')
    depth = 1
Run Code Online (Sandbox Code Playgroud)