I want to get Chapter model data as json , i used values() method and it works but it return book id not the book title and i want the book title
models.py
JavaScript
x
19
19
1
class Books(models.Model):
2
title = models.CharField(max_length=200 , unique=True)
3
slug = models.SlugField(max_length=255,unique=True)
4
data_id = models.IntegerField(unique=True)
5
6
def __str__(self):
7
return str(self.title)
8
9
10
11
12
class Chapter(models.Model):
13
book_id = models.ForeignKey(Books,on_delete=models.CASCADE)
14
source = models.CharField(max_length=100,blank=True)
15
chapter = models.CharField(max_length=10)
16
date = models.DateTimeField(auto_now_add=True)
17
def __str__(self):
18
return str(self.chapter)+" "+str(self.book_id)
19
views.py
JavaScript
1
5
1
class BookChapters(LoginRequiredMixin,View):
2
def get(self,request):
3
chapters = Chapter.objects.values()
4
return JsonResponse(list(chapters),safe=False)
5
json ouput
JavaScript
1
16
16
1
[
2
{
3
id: 1,
4
book_id: 237,
5
source: "nobel",
6
chapter: "18",
7
date: "2022-06-26T17:50:26Z"
8
},
9
{
10
id: 2,
11
book_id: 237,
12
source: "noble",
13
chapter: "19",
14
date: "2022-06-26T17:50:28Z"
15
}]
16
Advertisement
Answer
You can use ‘FK__COL’ in the values():
JavaScript
1
3
1
chapters = Chapter.objects.values('id', 'book_id__title', 'source', 'chapter', 'date')
2
return JsonResponse(list(chapters), safe=False)
3
Doc reference: https://docs.djangoproject.com/en/4.0/ref/models/querysets/#values