我正在尝试找到一种检查IntegerField
中给定对象ID是否存在的方法(用于序列化程序中的泛型关系),就像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')
serializers.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浏览器中字段不会突出显示。我想知道是否有更好的解决方案呢?提前谢谢!
答案 0 :(得分: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."
}
},
}
答案 1 :(得分:0)
我已经以某种方式做到了 - 删除了子类create
方法并添加了它:
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但外观与PrimaryKeyRelatedField
的外观不同。我认为有一些代码会检查抛出异常的位置,如果它来自该字段,那么它会以不同方式显示,否则默认情况下会显示异常。我想不出对这种行为的另一种解释,因为它提出了相同的ValidationError
。