0

Hi Hi.

I have a model

class Comment(models.Model):
    """ Comments model """

    cmnt_author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='cmnt_author',
        verbose_name='Comment author',
        null=True,
        blank=True,
        on_delete=models.CASCADE,
    )
    cmnt_txt = models.TextField(
        _('Text'),
        blank=True,
        max_length=480,
    )
    date_added = models.DateTimeField(
        _('Date added'),
        default=datetime.datetime.now
    )

    # Relationship with many models through ForeignKey
    content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        verbose_name='Content type',
    )
    object_id = models.PositiveIntegerField(
        null=True,
        verbose_name='Object ID',
    )
    content_object = GenericForeignKey('content_type', 'object_id')

And I have a serializer. I use this serializer to get comments.

class CommentSerializer(serializers.ModelSerializer):
    date_added = serializers.DateTimeField(format='%d %b %Y')

    class Meta:
        model = Comment
        fields = ('id', 'cmnt_avtr', 'author', 'cmnt_txt', 'date_added')

Question:

1) How can I use the same serializer to add comments? But to create a comment, I use fewer fields.

2) How to serialize adding comments when I use Generic Foreign Key

In particular, to add, I use these fields:

fields = ('cmnt_author', 'cmnt_txt', 'content_type', 'object_id',)
Coder Bug
  • 5
  • 3
  • 1
    Possible duplicate of [How to Serialize generic foreign key In DRF](https://stackoverflow.com/questions/34858206/how-to-serialize-generic-foreign-key-in-drf) – Brown Bear Feb 26 '19 at 07:18
  • https://stackoverflow.com/questions/47477489/django-rest-framework-writable-nested-serializers-with-generic-foreign-key – Brown Bear Feb 26 '19 at 07:18
  • I may not rightly put it I don't need read serialization. I just want to create a Comment object model. But since Generic Relations is registered in the commentary model, I would like to know how to create such an object? What data to override in serializer – Coder Bug Feb 26 '19 at 07:39

2 Answers2

0

You need to override create method in your serializer. Example:

def create(self, validated_data):
    # implement your logic here
    return Comment.objects.create(**validated_data)
Headmaster
  • 2,008
  • 4
  • 24
  • 51
  • I may not rightly put it I don't need read serialization. I just want to create a Comment object model. But since Generic Relations is registered in the commentary model, I would like to know how to create such an object? What data to override in serializer – Coder Bug Feb 26 '19 at 07:38
  • @CoderBug - If I get it right, you don't need serialization, while creating `Comment`? – Headmaster Feb 26 '19 at 07:40
  • Needed, but I do not know what data to transfer to me. I can transfer and create an object only with the fields 'cmnt_author', 'cmnt_txt', but I do not know what data and how to transfer to the serializer – Coder Bug Feb 26 '19 at 07:43
  • @CoderBug - can you explain `I do not know what data to transfer to me`? – Headmaster Feb 26 '19 at 07:44
  • `'cmnt_author': "id", 'cmnt_txt': "some text"` – Coder Bug Feb 26 '19 at 07:56
  • passing only these two arguments, I can easily create an object, but what do I have to pass so that the necessary model and its instance appear in the `content_type` and `object_id` fields – Coder Bug Feb 26 '19 at 07:59
0

Well, I figured it out. in my "view" I do the following

@action(detail=True, methods=['post'],)
def add_cmmnt(self, request, *args, **kwargs):
        data = {
            'cmnt_author': request.data.get('cmnt_author'),
            'cmnt_txt': request.data.get('cmnt_txt'),
            'content_type': ContentType.objects.get(model=kwargs.get('model')).id,
            'object_id': request.data.get('object_id'),
        }

        serializer = CommentSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response('ok')
Coder Bug
  • 5
  • 3