I would like to add foreign key fields to DRF serializer. I need API endpoint with information of Publication details with all Comments to this publication with all Images to this publication and with Likes number to this publication.
Models
class Publication(models.Model):
pub_text = models.TextField(null=True, blank=True)
pub_date = models.DateTimeField(auto_now_add=True)
pub_author = models.ForeignKey(User, on_delete=models.CASCADE)
class Comment(models.Model):
com_text = models.TextField(null=True, blank=True)
com_like = models.BooleanField(default=False)
com_author = models.ForeignKey(User, on_delete=models.CASCADE)
com_to_pub = models.ForeignKey(Publication, on_delete=models.CASCADE, related_name='comment_author')
com_date = models.DateTimeField(auto_now_add=True, null=True)
class Image(models.Model):
image = models.ImageField(upload_to='images', null=True)
image_to_pub = models.ForeignKey(Publication, on_delete=models.CASCADE, null=True, related_name='images')
Serializers
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = ['image']
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ['com_text', 'com_like', 'com_date', 'com_author']
class PublicationSerializer(serializers.ModelSerializer):
class Meta:
model = Publication
fields = ['id', 'pub_text', 'pub_author', 'pub_date']
def to_representation(self, instance):
representation = super().to_representation(instance)
representation['comment'] = CommentSerializer(instance.comment_author.all(), many=True).data
representation['image'] = ImageSerializer(instance.images.all(), many=True).data
return representation
Views
class PublicationViewSet(viewsets.ModelViewSet):
queryset = Publication.objects.all()
serializer_class = PublicationSerializer
class ImageViewSet(viewsets.ModelViewSet):
queryset = Image.objects.all()
serializer_class = ImageSerializer
class CommentViewSet(viewsets.ModelViewSet):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
By my logik Like to Publication can be given by Comment author if comment was created. I used <to_represtntation> method to add fields to Publication serializer. It works as i would need but not sure that was a good way to do. Also i cannot imagine how to add Likes number to Publication serializer.