Django rest framework foreign key display details from table 1 to table 2

30 views
Skip to first unread message

chern...@gmail.com

unread,
Jan 8, 2018, 11:58:22 PM1/8/18
to Django users
I have 2 model, MyUser, Family.

What i want to do is display users details in Family table based on the MyUser table. It is like adding friends or family in other social media and display them

In my current Family table, there are these 3 field. userId , familyId and relationship

userId(foreign key from MyUser table) = current user
familyId(foreign key from MyUser table) = current user's family member
relationship = who is the family member to the current user (eg: mother, father)

But i want to display **only some of** userId and familyId details from MyUser so the result will be like this:

**expected result**

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

    userId = 1
    familyId = 2
    relationship = father

How do i do it ? I thought about nested serializer but i only want to display user details but not edit it from there. 

Here is my code:

**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

Jason

unread,
Jan 9, 2018, 6:08:55 AM1/9/18
to Django users
What you are looking for is nested serialization.  There's a section in the DRF docs on this that should provide some light.  Fortunately, your serializers are almost there.

siva.gatti

unread,
Apr 5, 2018, 10:39:37 AM4/5/18
to Django users
did u get the solution for this if found send that to me
Reply all
Reply to author
Forward
0 new messages