How to map a custom type in Ming ODM?

281 Views Asked by At

I'm in the process of setting up a mapping in Ming ODM. One issue that has come up is how to map a custom type to a field, and how to pass that custom type into .query

Basically, I have an object to represent a Customer ID. I'd like the FieldProperty to take and return an object of this type, rather than one of the builtin types. The type is convertible to and from an int, and it will be stored as an int in Mongo, but in the data model and other Python code I want to pass it around as this domain-specific type.

When passing an instance of CustomerID type directly as a kwd argument to .query, PyMongo complains that it doesn't understand the type.

1

There are 1 best solutions below

0
On

I recently wanted to do something similar; storing IP Addresses as binary data in MongoDB through Ming. (The reason for this was to allow efficient CIDR queries.) I'm providing my solution for anyone else who happens to come across this question while trying the same thing, even though it may be too late to help @kbluck.

I made this work though the trick of making my IP address class a subclass of bson.Binary (I'm using Python 2; for Python 3, a subclass of the builtin binary type would be used instead).

You would make your CustomerID class a subclass of int. The CustomerID class needs to have a polymorphic constructor that accepts an int (for when loading from the database), a CustomerID instance (copy constructor), and whatever constructor the application needs to use (in my example an IP address presentation string).

This is not quite what you asked for; the FieldProperty takes either an int or your type and returns a special int that knows how to be converted to your type.

I've uploaded a full example (of IP addresses) as a gist: https://gist.github.com/3854792