Home > Enterprise >  Django rest framework get data from foreign key relation?
Django rest framework get data from foreign key relation?

Time:08-14

I have a models like this:

class Author(models.Model):
    name = models.CharField(max_length=150, blank=False, null=False)
    dob = models.DateField(null=True, blank=True)
    description = models.TextField(max_length=2000, blank=False, default="This author doesn't have any description yet!")
    image = models.ImageField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['created']

    def __str__(self):
        return self.name


class Book(models.Model):
    title = models.CharField(max_length=200, blank=False, null=False)
    author = models.CharField(max_length=200)
    genres = models.ManyToManyField(Genre, related_name='genre', blank=True)
    author = models.ForeignKey(Author, related_name='author', blank=True, on_delete=models.CASCADE)
    description = models.TextField(max_length=1200, blank=False, default="This book doesn't have description yet!")
    image = models.ImageField(default="")
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['created']

    def __str__(self):
        return self.title


class Review(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, null=False, blank=False, help_text="Title overall of your review")
    rating = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(5)], help_text='Rating in range 0-5')
    description = models.TextField(max_length=1000, null=False, blank=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

I want to get Book data response in json with my reviews of the book from my Review table but don't know how. I am not getting any useful solution from documentation and Google, please help.

CodePudding user response:

You could set the related_name field in the book field of the Review model.

class Review(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name = 'reviews')
    ...

Then in the serializer, you can add the related field.

class ReviewSerializer(serializers.ModelSerializer):
    class Meta:
        model = Review
        fields = '__all__'

class BookSerializer(serializers.ModelSerializer):
    reviews = ReviewSerializer(many = True)

    class Meta:
        model = Book
        fields = '__all__'
        extra_fields = ('reviews', )
  • Related