习惯于从Tastypie过来的Django Rest Framework,但是在涉及ManyToMany字段时遇到了问题 .
当字段需要序列化时,首选它包括其完整的表示,这可以通过添加一个ModelSerializer很多来实现,其中有许多= True和read_only = True . 问题是这使我无法保存帐户字段,因为它现在显示为空白 .
如果我尝试删除read_only = True我得到
TypeError: 'accounts' is an invalid keyword argument for this function
最好发送完整的表示,但在接收相关的POST(创建)或PUT(更新)时只需要ID .
POST:
{
"profile" : "1",
"accounts" : ["1"],
"amount" : "101.00"
}
响应:
{
"id": 92,
"accounts": [],
"date_by": null,
"amount": "101.00",
"shared": false,
"profile": 1
}
得到:
[
{
"id": 45,
"accounts": [
{
"account_local": {
"id": 3,
"last_balance": "100.00",
},
"type": "LocalAccount"
}
],
"date_by": null,
"amount": "100.00",
"shared": false,
"profile": 1
},]
GoalSerializer
class GoalSerializer(serializers.ModelSerializer):
accounts = AccountSerializer(many=True, read_only=True)
class Meta:
model = Goal
GoalViewSet
class GoalViewSet(GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.CreateModelMixin):
serializer_class = GoalSerializer
queryset = Goal.objects.none()
def get_queryset(self):
return Goal.objects.filter(profile=self.request.user)
AccountSerializer
class AccountSerializer(serializers.ModelSerializer):
type = SerializerMethodField('get_account_class')
class Meta:
model = Account
fields = ('account_local','account_external', 'type')
depth = 1
def get_account_class(self, obj):
if isinstance(obj.get_actual(), LocalAccount):
return obj.get_actual().__class__.__name__
elif isinstance(obj.get_actual(), ExternalAccount):
return obj.get_actual().get_actual().__class__.__name__
else:
return "Error"
def to_representation(self, instance):
data = super(AccountSerializer, self).to_representation(instance)
if isinstance(instance.get_actual(), ExternalAccount):
serializer = ExternalAccountSerializerEMT(instance.account_external.get_actual())
data['account_external'] = serializer.data
return data
1 回答
我设法绕过这个:
用a更改 AccountSerializer
def to_internal_value(self, data): return Account.objects.get(id=data)
删除字段上的read_only属性
accounts = AccountSerializer(many=True)
在POST'ing / PUT时,该帐户只需要是一个id,并且在GET'ing时返回整个帐户