Django休息框架外键显示从表1到表2的详细信息

时间:2018-01-09 07:00:27

标签: django django-rest-framework

我有2个型号,MyUser,Family。

我想要做的是根据MyUser表在Family表中显示用户详细信息。这就像在其他社交媒体中添加朋友或家人并显示它们

在我目前的Family表中,有这3个字段。 userId,familyId和relationship:

userId(来自MyUser表的外键)=当前用户

familyId(来自MyUser表的外键)=当前用户的家庭成员

relationship =谁是当前用户的家庭成员(例如:母亲,父亲)

但是我想在MyUser中显示只有部分 userId和familyId详细信息,结果如下:

预期结果

userId = { id = 1, username = tom, image = "/media/images1/asdasdsda000.PNG"}
familyId = { id = 2, username = steve, image = "/media/images1/asdasdsda111.PNG"}
relationship = father

当前结果

userId = 1
familyId = 2
relationship = father

我该怎么做?我想过嵌套的序列化程序,但我只想显示用户详细信息,但不想从那里编辑它。

这是我的代码:

models.py

class MyUser(AbstractUser):
    userId = models.AutoField(primary_key=True)
    image1 = models.ImageField(upload_to='images1')
    dob = models.DateField(blank=True, null=True)
    gender = models.CharField(max_length=6)

class Family(models.Model):
    userId = models.ForeignKey(MyUser)
    familyId = models.ForeignKey(MyUser)
    relationship = models.CharField(max_length = 20)

serializer.py

class MyUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyUser
        fields = ['userId', 'username', 'email', 'first_name', 'last_name', 'image']
        read_only_fields = ('userId',)
        extra_kwargs = {"password": {"write_only": True}}

class FamilySerializer(serializers.ModelSerializer):
    class Meta:
        model = Family
        fields = ('id', 'userId', 'familyId', 'relationship')

views.py

class MyUserViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = MyUser.objects.all()
    serializer_class = MyUserSerializer

class MyUserViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = Family.objects.all()
    serializer_class = FamilySerializer

1 个答案:

答案 0 :(得分:0)

您可以使用NestedSerializer

class MyUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyUser
        fields = ['userId', 'username', 'email', 'first_name', 'last_name', 'image']
        read_only_fields = ('userId',)
        extra_kwargs = {"password": {"write_only": True}}

class FamilySerializer(serializers.ModelSerializer):
    user = MyUserSerializer()
    family = MyUserSerializer()    
    class Meta:
        model = Family
        fields = ('id', 'user', 'family', 'relationship')