Django 静止框架中的只写、只读字段

我有这样的模型:

class ModelA(models.Model):
name = models.CharField()




class ModelB(models.Model):
f1 = models.CharField()
model_a = models.ForeignKey(ModelA)

序列化器:

class ASerializer(serializers.ModelSerializer):
model_b_ids = serializers.CharField()
class Meta:
model = ModelA
write_only_fields = ('model_b_ids',)

观点:

class AView(CreateModelMixin, GenericViewSet):


def perform_create(self, serializer):
model_b_ids = parse_somehow(serializer.validated_data["model_b_ids"])
#do something...

我遇到的问题是“ model _ b _ ids”

用户应该在发送文章数据时提交它。

我使用它在 Performance _ create 中链接到相关的模型。

但是这并不是 ModelA 中的“真正的列”,所以当我试图保存它时会引发异常。

我试图从 valid_ data 中弹出它,但是在无法从 model 中读取 model _ b _ ids 的地方又出现了错误。对于正确使用这种字段有什么想法吗?

137639 次浏览

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.

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

The Django Rest Framework does not have Meta attribute write_only_fields anymore

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}
}

Update

As @AKHIL MATHEW highlighted in his answer below

From DRF v3 onwards, setting a field as read-only or write-only can use serializer field core arguments mentioned as follows.

write_only

Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

Defaults to False Eg:

company = serializers.PrimaryKeyRelatedField(write_only=True)

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},
'another_field': {'read_only': True}
}

or:

 model_b_ids = serializers.IntegerField(write_only=True)

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}
}

From DRF v3 onwards, setting a field as read-only or write-only can use serializer field core arguments mentioned as follows.

Core arguments

Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:

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

Eg:

price = serializers.IntegerField(read_only=True)

write_only

Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.

Defaults to False

Eg:

company = serializers.PrimaryKeyRelatedField(write_only=True)