DRF序列化通用外键

时间:2019-02-25 16:52:44

标签: python serialization django-rest-framework

嗨。

我有一个模特

func majorityElement(_ nums1: [Int]) -> Int? { // you should probably return an optional here in case nums1 is empty

    let num1Dict = Dictionary(nums1.map{ ($0, 1) }, uniquingKeysWith : +)
    var currentHigh = Int.min
    var mostOccurence: Int?
    for kvp in num1Dict {
        if kvp.value > currentHigh {
            mostOccurence = kvp.key
            currentHigh = kvp.value
        }
    }
    return mostOccurence

}

我有一个序列化器。 我使用此序列化程序来获取评论。

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')

问题:

1)如何使用相同的序列化器添加注释? 但是要创建评论,我使用的字段较少。

2)当我使用通用外键

时,如何序列化添加注释

特别是,我使用以下字段:

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')

2 个答案:

答案 0 :(得分:0)

您需要在序列化程序中覆盖create方法。示例:

def create(self, validated_data):
    # implement your logic here
    return Comment.objects.create(**validated_data)

答案 1 :(得分:0)

好吧,我知道了。 在我的“视图”中,我执行以下操作

@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')