django通过很多很多

时间:2017-03-01 13:37:32

标签: python django django-rest-framework

我正在尝试实施一个教练系统,我对django中的序列化感到有些迷失。我有很多通过模型来控制约会,我想获得有关教练/教练参与的所有数据关系。

class Appointment(models.Model):
    """docstring for Appointment"""
    coach = models.ForeignKey(User, related_name='coaches', on_delete=models.CASCADE)
    coachee = models.ForeignKey(User, related_name='coachees', on_delete=models.CASCADE)
    schedule_date = models.DateField(auto_now=False, auto_now_add=True, blank=True)
    due_date = models.DateField()
    summary = models.TextField(max_length=200)

使用以下序列化程序,我可以获得主键,但我真的想在一个请求中获取coach和coachee详细信息。

#return appointment data
class AppointmentSerializer(serializers.HyperlinkedModelSerializer):
    """docstring for AppointmentSerializer"""
    class Meta:
        model = Appointment
        fields = ('id', 'schedule_date', 'due_date', 'coach', 'coachee', 'summary', 'condition')

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。常见的是为用户创建序列化程序并使用它而不是默认字段:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ...

class AppointmentSerializer(serializers.ModelSerializer):
    coach = UserSerializer()
    coachee = UserSerializer()

    class Meta:
        model = Appointment
        fields = ('id', 'schedule_date', 'due_date', 'coach', 'coachee', 'summary', 'condition')

但如果您想使用AppointmentSerializer创建实例,则会出现问题。您将无法将id的用户传递到该字段。在这种情况下,您可以使用默认字段并覆盖to_representation方法。

class AppointmentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Appointment
        fields = ('id', 'schedule_date', 'due_date', 'coach', 'coachee', 'summary', 'condition')

    def to_representation(self, instance):
        representation = super(AppointmentSerializer, self).to_representation(instance)
        representation['coach'] = UserSerializer(instance.coach).data
        representation['coachee'] = UserSerializer(instance.coachee).data
        return representation

答案 1 :(得分:1)

尝试在depth类上设置Meta选项。

class AppointmentSerializer(serializers.HyperlinkedModelSerializer):
    """docstring for AppointmentSerializer"""
    class Meta:
        model = Appointment
        fields = ('id', 'schedule_date', 'due_date', 'coach', 'coachee', 'summary', 'condition')
        depth = 1

这将生成嵌套表示。

或者,如果需要更多控制,可以显式指定序列化程序。

class AppointmentSerializer(serializers.HyperlinkedModelSerializer):
    coach = CoachSerializer()
    coachee = CoacheeSerializer()

    class Meta:
        model = Appointment
        fields = ('id', 'schedule_date', 'due_date', 'coach', 'coachee', 'summary', 'condition')

您还可以添加相关模型中的单个字段:

class AppointmentSerializer(serializers.HyperlinkedModelSerializer):
    """docstring for AppointmentSerializer"""
    coach_name = serializers.CharField(source='coach.name')

    class Meta:
        model = Appointment
        fields = ('id', 'schedule_date', 'due_date', 'coach', 'coachee', 'summary', 'condition')