Django DRF嵌套项

时间:2018-01-23 09:40:34

标签: django django-rest-framework

我尝试从POST请求中创建一组对象,在此我发送应该创建的对象的pk列表:

data = { 'a_ref':["17629","17630","17631"] }
x= Model_Serializer(data=data)

这是我的序列化器:

class A_Serializer(serializers.ModelSerializer):
    class Meta:
        model = A
        fields = ('pk',)

class Model_Serializer(serializers.ModelSerializer):
    a_ref = A_Serializer( many=True)


    def create(self, validated_data):
        tracks_data = validated_data.pop('a_ref')
        model = Model.objects.create(**validated_data)

        for track_data in tracks_data:
            A.objects.create(ref=model, **track_data)
        return model

    class Meta:
        model = models.Model

但我明白了:

[14]: x.is_valid()
Out[14]: False


x.errors
Out[16]: 
ReturnDict([
            ('a_ref',
             [{'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']},
              {'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']},
              {'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']}])])

2 个答案:

答案 0 :(得分:0)

由于import RxSwift import RxCocoa struct NewControlViewModel { var selectedClient = Variable<Client>(Client()) // other stuff } // NewControlTableViewController : viewDidLoad viewModel.selectedClient.asObservable().subscribe { event in debugPrint(event) } // ClientsTableViewController: viewDidLoad /*tableView.rx.itemSelected.subscribe(onNext: { indexPath in let client = self.clients[indexPath.row] debugPrint(client) self.viewModel.selectedClient.value = client self.navigationController?.popToRootViewController(animated: true) }).disposed(by: self.disposeBag)*/ // new code tableView.rx .modelSelected(Client.self) .debug("client selected", trimOutput: true) .do(onNext: { _ in self.navigationController?.popViewController(animated: true) }) .subscribe(onNext: { client in debugPrint(client) self.viewModel.selectedClient.value = client }, onError: { error in debugPrint(error) }).disposed(by: disposeBag) 是序列化程序,因此要为此字段发送的数据应为对象列表。就像这样

a_ref

答案 1 :(得分:0)

这有用吗?

for track_data in tracks_data:
    temp_dict = {'pk':track_data}
    A.objects.create(ref=model, **temp_dict)
return model