DRF:如何在序列化程序中将模型方法返回的序列化对象包含为字段?

时间:2016-05-26 08:29:11

标签: python django serialization django-models django-rest-framework

DRF新手在这里。

我正在尝试为学校项目构建API。我的项目树包括几个应用程序,一个是Profiles,另一个是Trips。

profiles.models包含Driver和DriverSession模型。 trips.models包括Trip Model。

下面你可以看到我在profiles.models中创建的DriverSession模型。我添加了一个模型方法'get_active_trip',以便能够在检索到相应的DriverSession时将驱动程序的活动行程(如果它存在)返回给客户端应用程序。如果它不存在,我希望trip字段仍然包含在响应中,其值为None。

class DriverSession(models.Model):
    driver = models.ForeignKey(Driver)
    vehicle = models.ForeignKey(Vehicle)
    start_timestamp = models.DateTimeField(auto_now_add=True)
    end_timestamp = models.DateTimeField(null=True, blank=True)

    class Meta:
        verbose_name = 'DriverSession'
        verbose_name_plural = 'Driver Sessions'

    # Model method to get active trip of the driver
    def get_active_trip(self):

        try :
            trip = Trip.objects.get(driver_session=self, Q(status='DI') | Q(status='OT'))
        except Trip.DoesNotExist :
            return None
        else :
            return trip

这是我在profiles.models中为DriverSession模型创建的Serializer:

from trips.serializers import TripSerializer

class DriverSessionSerializer(serializers.ModelSerializer):
    """
    Serializer class for DriverSession Model.
    """

    driver = DriverSerializer(read_only=True)
    driver_id = serializers.IntegerField(write_only=True)

    vehicle = VehicleSerializer(read_only=True)
    vehicle_id = serializers.IntegerField(write_only=True)

    start_timestamp = serializers.DateTimeField(read_only=True,format='%Y-%m-%d %H:%M:%S')
    end_timestamp = serializers.DateTimeField(required=False, allow_null=True, format='%Y-%m-%d %H:%M:%S')

    trip = TripSerializer(source='get_active_trip', read_only=True)

    class Meta:
        model = DriverSession
        fields = ('id',
                  'driver',
                  'driver_id',
                  'vehicle',
                  'vehicle_id',
                  'start_timestamp',
                  'end_timestamp',
                  'trip')

这是我的旅行模型在trip.models中的局部视图:

class Trip(models.Model):
    rider = models.ForeignKey('profiles.Rider')
    driver_session = models.ForeignKey('profiles.DriverSession', null=True, blank=True)
    ....
    ....

最后,以下是我在trip.serializers中为Trip Model创建的序列化程序类的局部视图:

from profiles.serializers import DriverSessionSerializer

class TripSerializer(drf_serializers.ModelSerializer):
    """
    Serializer class for Trip model
    """
    ....
    ....


    driver_session = DriverSessionSerializer(read_only=True)
    driver_session_id = drf_serializers.IntegerField(write_only=True, required=False, allow_null=True)

    ....
    ....

当我尝试运行命令'runserver'时,我在trips.serializers中遇到导入错误,其中无法导入任何profiles.serializers。

我在这里缺少什么?如何将模型的相应序列化器中的模型方法返回的序列化对象包含为字段?

1 个答案:

答案 0 :(得分:1)

您想将自定义字段添加到您的血清器中 你必须做这样的代码:

class FooSerializer(serializers.ModelSerializer):
  my_field = serializers.SerializerMethodField('is_named_bar')

  def is_named_bar(self, foo):
      return foo.name == "bar" 

  class Meta:
    model = Foo
    fields = ('id', 'name', 'my_field')

http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield