I have a serializer called EntrySerializer and it should return the staff details but if I want to create a new entry it wants to create a new staff object and throws an error. Is there anything like a read only field for my serializer? It should create a new entry but assign an already created staff object.
class EntrySerializer(serializers.ModelSerializer):
staff = serializers.SerializerMethodField('get_staff')
def get_staff(self, obj):
return MyUserSerializer(obj.staff).data
class Meta:
model = Entry
depth = 1
fields = ('time_spend', 'staff',)
Error:
django.db.utils.IntegrityError: ERROR: NULL-value in Column »staff_id« relation »tagesbericht_tagesbericht_Entry« Not-Null-Constraint DETAIL: (54, 00:00:08.5, null, 61).
POST:
"tagesbericht_entry_set": [ { "staff": 2, "time_spend": "00:12:08" } ]
CodePudding user response:
I think you need to add the staff_id
field for writing.
class EntrySerializer(serializers.ModelSerializer):
staff = MyUserSerializer(read_only = True)
staff_id = Serializers.IntegerField(write_only = True)
class Meta:
model = Entry
depth = 1
fields = ('time_spend', 'staff', 'staff_id')
And the POST payload should be
{
"staff_id": 2,
"time_spend": "00:12:08"
}