我想保存模型,但是一个字段必须从db获取数据。
更好地显示代码来说明我的意图
class LoyaltyUserCreateSerializer(serializers.ModelSerializer):
account = serializers.SerializerMethodField()
class Meta:
model = LoyaltyUser
fields = [
'name',
'last_name',
'gender',
'email',
'phone',
'birth_date',
'account'
]
def get_account(self, obj):
return Account.objects.get(pk=self.context['request'].user.pk)
我发送的数据
{"name": "Petr1", "last_name": "Petrov", "gender": "male", "email": "email", "phone": "123", "birth_date": "2018-12-12"}
问题是,当我尝试使用CreateAPI保存它时,出现500错误
IntegrityError at /api/create_user
NOT NULL constraint failed: core_loyaltyuser.account_id
查看
class LoyaltyUserCreateAPIView(CreateAPIView):
queryset = LoyaltyUser.objects.all()
serializer_class = LoyaltyUserCreateSerializer
答案 0 :(得分:2)
覆盖CreateAPIView的perform_create
方法:
class LoyaltyUserCreateAPIView(CreateAPIView):
queryset = LoyaltyUser.objects.all()
serializer_class = LoyaltyUserCreateSerializer
def perform_create(self, serializer):
serializer.save(account_id=self.request.user.pk) # updated after feedback
请参见docs
此外,您无需在序列化程序中将account
定义为serializers.SerializerMethodField()
,它用于只读。 (例如,您需要发送一些额外的数据作为响应,而不仅仅是account
的ID)
改为将其添加到read_only_fields:
class LoyaltyUserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = LoyaltyUser
fields = (
'name',
'last_name',
'gender',
'email',
'phone',
'birth_date',
'account'
)
read_only_fields = ('account',)