gbrennon
gbrennon

Reputation: 979

How to handle and test Mongoengine objects with ReferenceField?

So,

I'm writing a REST Api with Flask-RESTful, MongoEngine and marshmallow and I'm with some issues on testing my models that have ReferenceFields.

I have a "Praia" model that have a "atividades" ReferenceField.

When I pass

class PraiasSerializer(Schema):
  id = fields.String()
  atividades = fields.Nested(AtividadesSerializer, many=True)

  class Meta:
    additional = ('nome', 'descricao')

model = {'nome': 'nome', 'descricao': 'descricao',
          atividades: [ativ1.id, ativ2.id]}
praia = Praias(**model)
data = PraiasSerializer(praia).data
data.pop('id')
self.client.post('/v1/praias', data=data,
                 content_type='application/json')

Even with this data.pop('id') to make my model not send 'id' to my controller I receive a TypeError: add_file() got an unexpected keyword argument 'id'

When I print this data variable I get the following output:

{u'atividades': [{u'id': u'5501dee0e13823649320299d'}, {u'id': u'5501dee0e13823649320299c'}], u'descricao': u'Portao e sucesso!', u'nome': u'Porto da Barra'}

What should I do?

Upvotes: 0

Views: 412

Answers (1)

gbrennon
gbrennon

Reputation: 979

I've found the answer!

I just changed the way I mounted the json data for the post request.

Instead of using my Serializer or json.dumps(Model) I'm using:

model = {'nome': 'nome', 'descricao': 'descricao',
          atividades: [str(ativ1['id']), str(ativ2['id'])]}
data = json.dumps(model)

I did a cast to str on id because Python doesn't know how to JSON serialize the ObjectId.

Now the request just works!

Upvotes: 2

Related Questions