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
class Books(models.Model): title = models.CharField(max_length=200 , unique=True) slug = models.SlugField(max_length=255,unique=True) data_id = models.IntegerField(unique=True) def __str__(self): return str(self.title) class Chapter(models.Model): book_id = models.ForeignKey(Books,on_delete=models.CASCADE) source = models.CharField(max_length=100,blank=True) chapter = models.CharField(max_length=10) date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.chapter)+" "+str(self.book_id)
views.py
class BookChapters(LoginRequiredMixin,View): def get(self,request): chapters = Chapter.objects.values() return JsonResponse(list(chapters),safe=False)
json ouput
[ { id: 1, book_id: 237, source: "nobel", chapter: "18", date: "2022-06-26T17:50:26Z" }, { id: 2, book_id: 237, source: "noble", chapter: "19", date: "2022-06-26T17:50:28Z" }]
Advertisement
Answer
You can use ‘FK__COL’ in the values():
chapters = Chapter.objects.values('id', 'book_id__title', 'source', 'chapter', 'date') return JsonResponse(list(chapters), safe=False)
Doc reference: https://docs.djangoproject.com/en/4.0/ref/models/querysets/#values