1

我试图找到一种方法来检查给定的对象 ID 是否IntegerField存在(用于序列化程序中的通用关系),就像PrimaryKeyRelatedField.

到目前为止,我采用了这种方法:
models.py:

class Comment(models.Model):
    person = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    content_type = models.ForeignKey(ContentType, limit_choices_to={'pk__in': CONTENT_TYPES_PK})
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

序列化程序.py:

class CommentSerializer(serializers.ModelSerializer):
    person = UserSerializer(read_only=True, default=serializers.CurrentUserDefault())
    content_type = serializer.PrimaryKeyRelatedField(queryset=ContentType.objects.filter(pk__in=CONTENT_TYPES_PK), write_only=True)
    object_id = IntegerField(write_only=True)

    class Meta:
        model = Comment
        extra_kwargs = {'created': {'read_only': True}}
        exclude = ('content_object',)

    def create(self, validated_data):
        obj = Comment(**validated_data)
        if not obj.content_object:
            raise serializers.ValidationError({'object_id': ['Invalid pk "'+str(obj.object_id)+'" - object does not exist.']})
        obj.save()
        return obj

但这不是一种可靠的方法,因为它实际上不会引发字段错误 - 它只是模仿它,因此在 API 浏览器中该字段没有突出显示。我想知道是否有更好的解决方案?提前致谢!

PS这是提交表单后的样子:

4

2 回答 2

3

用户extra_kwargs 简单易申请我分享请在序列化器字段后申请。

class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = testModel
        fields = ('id','state','city','first_name',)
        extra_kwargs = {
            "state": {
                'allow_null': False, 'required': True,
                "error_messages" : {
                    "null" : "State is mandatory.",
                    "invalid": "State should be valid id",
                    "incorrect_type": "State should be valid id",
                    "does_not_exist": "State should be valid id",
                    "required":"State is mandatory.",
                    "blank":"State is mandatory."
                }
             },
         }
于 2018-02-27T11:12:06.957 回答
1

I've made it somehow - removed subclassed create method and added this instead:

def validate(self, attrs):
    try:
        attrs['content_object'] = attrs['content_type'].model_class().objects.get(pk=attrs['object_id'])
    except:
        raise serializers.ValidationError({'object_id': ['Invalid pk "'+str(attrs['object_id'])+'" - object does not exist.']})
    return attrs

It now highlights the field but the appearance differs from the one for PrimaryKeyRelatedField. I think that there's some code which checks from where the exception is thrown, and if it's from that field then it shows it differently, else it goes by default. I couldn't think of another explanation for that behavior, because it raises the same ValidationError.

于 2016-08-29T12:10:09.963 回答