You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`.
@@ -505,6 +505,19 @@ This option should be a list or tuple of field names, and is declared as follows
505
505
506
506
Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option.
507
507
508
+
---
509
+
510
+
**Note**: There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. Here you **must** specify the field explicitly and provide a valid default value.
511
+
512
+
A common example of this is a read-only relation to currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so:
513
+
514
+
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
515
+
516
+
Please review the [Validators Documentation](/api-guide/validators/) for details on the [UniqueTogetherValidator](/api-guide/validators/#uniquetogethervalidator) and [CurrentUserDefault](/api-guide/validators/#currentuserdefault) classes.
517
+
518
+
---
519
+
520
+
508
521
## Specifying additional keyword arguments for fields.
509
522
510
523
There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. Similarly to `read_only_fields` this means you do not need to explicitly declare the field on the serializer.
@@ -516,7 +529,7 @@ This option is a dictionary, mapping field names to a dictionary of keyword argu
516
529
model = User
517
530
fields = ('email', 'username', 'password')
518
531
extra_kwargs = {'password': {'write_only': True}}
519
-
532
+
520
533
def create(self, validated_data):
521
534
user = User(
522
535
email=validated_data['email'],
@@ -656,7 +669,7 @@ To support multiple updates you'll need to do so explicitly. When writing your m
656
669
* How do you determine which instance should be updated for each item in the list of data?
657
670
* How should insertions be handled? Are they invalid, or do they create new objects?
658
671
* How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid?
659
-
* How should ordering be handled? Does changing the position of two items imply any state change or is it ignored?
672
+
* How should ordering be handled? Does changing the position of two items imply any state change or is it ignored?
660
673
661
674
Here's an example of how you might choose to implement multiple updates:
0 commit comments