2017-03-01 69 views
2

我想實現一個教練系統,我有點在django中的序列化丟失。我有一個多對多的模型來控制約會,我想獲得有關教練/ coachee參與了關係。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) 

使用下面的序列化,我可以得到所涉及的主鍵,但我真的很想得到一個請求教練和教練者的詳細信息。

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

哇,這是速度快,非常有用。我使用深度= 1選項,它的工作!非常感謝你。作爲新手,我非常感謝大家的幫助 –

回答

1

嘗試設置在Metadepth選項。

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') 
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