Django(DRF):以不同方式序列化和反序列化ManyToMany字段?

时间:2016-04-24 02:20:38

标签: python django django-rest-framework

习惯从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
}

GET:

[
  {
    "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 个答案:

答案 0 :(得分:1)

我设法绕过这个:

  • 用<更改 AccountSerializer std::string line; std::vector<std::string> names; while ( getline( cin, line)) { if(line.empty()) { // end input condition break; } std::istringstream iss(line); std::string name; while(iss >> name) { names.push_back(name); } }

  • 删除字段上的read_only属性

    def to_internal_value(self, data): return Account.objects.get(id=data)

帐户只需要在POST'ing / PUT'时成为id,并且在GET'ing时返回整个帐户