I am currently working on a tutoring API using Python and Django. I want the Tutor Model to show all the tutees (yes, that is a word) and the tutee to show the tutor. Right now, it works correctly but it references the id/pk of the model so I really don't know who or what it refers to.
GET a tutee :
{
"id": 1
"full_name": "First Last",
"email": "email@emailprovidercom",
"tutor": 1,
"subjects": "SubjectX"
}
As you can see, the tutor is a number instead of a name.
GET a tutor:
{
"id": 1,
"full_name": "First Last",
"email": "[email protected]",
"notes": "XXXXX XX XX X X X X X X XXXXXX XX X X X X ",
"tutees": [
1
]
}
The same thing happens here.
I am using Django Rest Framework.
My models
class Tutor(models.Model):
full_name = models.CharField(max_length=40)
email = models.EmailField()
notes = models.TextField()
def __str__(self):
return self.full_name
class Tutee(models.Model):
full_name = models.CharField(max_length=40)
email = models.EmailField()
tutor = models.ForeignKey(Tutor, on_delete=models.CASCADE, related_name="tutees")
subjects = models.CharField(max_length=13)
def __str__(self):
return self.full_name
My Serializers
class TutorSerializer(serializers.ModelSerializer):
class Meta:
model = Tutor
fields = ['id', 'full_name', 'email', 'notes', 'tutees']
class TuteeSerializer(serializers.ModelSerializer):
class Meta:
model = Tutee
fields = ['id', 'full_name', 'email', "tutor", "subjects"]
My Viewsets
class TutorAPI(viewsets.ModelViewSet):
queryset = Tutor.objects.all()
serializer_class = TutorSerializer
permission_classes = [permissions.IsAuthenticated]
lookup_field = "full_name"
class TuteeAPI(viewsets.ModelViewSet):
queryset = Tutee.objects.all()
serializer_class = TuteeSerializer
permission_classes = [permissions.IsAuthenticated]
lookup_field = "full_name"
If you need more, please comment and I will edit my question! Even if you just mark it as duplicate, that would be helpful.
question from:
https://stackoverflow.com/questions/65832034/how-to-get-django-to-reference-the-name-instead-of-the-id-pk 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…