问题
I have models like this:
class ModelA(models.Model):
name = models.CharField()
class ModelB(models.Model):
f1 = models.CharField()
model_a = models.ForeignKey(ModelA)
Serializers:
class ASerializer(serializers.ModelSerializer):
model_b_ids = serializers.CharField()
class Meta:
model = ModelA
write_only_fields = ('model_b_ids',)
views:
class AView(CreateModelMixin, GenericViewSet):
def perform_create(self, serializer):
model_b_ids = parse_somehow(serializer.validated_data["model_b_ids"])
#do something...
The problem I am getting is the with the "model_b_ids"
The user should submit it while sending post data.
I use it in perform_create to link to related models.
But thats not "real column" in ModelA so when I try to save it is raising exception.
I tried to it pop from validated_data but then again getting error somewhere that cannot read model_b_ids from model. Any idea on using this kind of field correctly ?
回答1:
Correct me if im wrong but i dont think django rest framework has Meta attribute
write_only_fields
According to their docs you set write only fields in extra_kwargs
e.g
class UserSerializer(ModelSerializer):
"""
``Serializer`` for ``User`` ..
"""
class Meta:
model = User
fields = ('id', 'email', 'first_name', 'last_name' ,'security_question', 'security_question_answer', 'password', 'is_active', 'is_staff')
read_only_fields = ('is_active', 'is_staff')
extra_kwargs = {
'security_question': {'write_only': True},
'security_question_answer': {'write_only': True},
'password': {'write_only': True}
}
回答2:
In accordance with the Django REST Framework documentation:
The write_only_fields option on ModelSerializer has been moved to PendingDeprecation and replaced with a more generic extra_kwargs
that's why it's recommended to do like this: you should use extra_kwargs:
extra_kwargs = {'model_b_ids': {'write_only': True}}
or:
model_b_ids = serializers.IntegerField(write_only=True)
回答3:
Probably you're overseeing that your ModelA
has the property modelb_set
. In Django you describe the relationship in one model class. Django offers a backward relationship by lower-casing the target model and suffixing it with _set
. So you could do:
a = ModelA.objects.get(pk=1)
a.modelb_set.all()
This would get the element with ID (or primary key) 1 from ModelA and retrieve all related ModelB elements.
You can set a value for related_name
to overwrite the default value:
class ModelB(models.Model):
f1 = models.CharField()
model_a = models.ForeignKey(ModelA, related_name='model_b')
In DRF you can slightly adapt your serializer:
class ASerializer(serializers.ModelSerializer):
model_b = serializers.PrimaryKeyRelatedField(many=True, read_only=False)
class Meta:
model = ModelA
write_only_fields = ('model_b',)
With serializers.CharField()
you can't post values and write them to the model, because it isn't a model field.
Give this example a try. Tinker and experiment. It should bring you closer to the solution.
EDIT:
I'm not really sure how Django creates the name for backward relationship for PascalCase class names. Is it model_b_set
for ModelB
? Or is it modelb_set
? You can try and find it out.
回答4:
From docs you can use read_only
Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.
Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.
Defaults to
False
As example:
We can use it on Serializer fields:
model_b_ids = serializers.IntegerField(read_only=True)
or we can use it in extra_kwargs
:
extra_kwargs = {
'model_b_ids': {'read_only': True}
}
回答5:
Well you could override the serializer.save() method on ASerializer to instantiate modelA object, set its attributes, save it, then set relations on existing modelB objects, save them as well and drink to success. But I think maybe setting that related_name and RelatedField on serializer as was suggested would do exactly the same thing.... with less typing.. and overall better:)
来源:https://stackoverflow.com/questions/34989915/write-only-read-only-fields-in-django-rest-framework