Skip to content

Polymorphic queries #30

@bitozoid

Description

@bitozoid

I have replicated the example in https://ming.readthedocs.io/en/latest/polymorphism.html.

I have added a Bike and can reproduce the queries below as in the documentation.

from ming import schema
from ming.odm import FieldProperty
from ming.odm.declarative import MappedClass

class Transport(MappedClass):
    class __mongometa__:
        session = session
        name = 'transport'
        polymorphic_on = '_type'
        polymorphic_identity = 'base'

    _id = FieldProperty(schema.ObjectId)
    origin = FieldProperty(schema.String(required=True))
    destination = FieldProperty(schema.String(if_missing=''))
    _type = FieldProperty(schema.String(if_missing='base'))

    def move(self):
        return 'moving from {} to {}'.format(self.origin, self.destination)

class Bus(Transport):
    class __mongometa__:
        polymorphic_identity = 'bus'

    _type=FieldProperty(str, if_missing='bus')
    passengers_count = FieldProperty(schema.Int(if_missing=0))

    def move(self):
        return 'driving from {} to {}'.format(self.origin, self.destination)


class AirBus(Bus):
    class __mongometa__:
        polymorphic_identity = 'airbus'

    _type=FieldProperty(str, if_missing='airbus')
    wings_count = FieldProperty(schema.Int(if_missing=2))

    def move(self):
        return 'flying from {} to {}'.format(self.origin, self.destination)

class Bike(Transport):
    class __mongometa__:
        polymorphic_identity = 'bike'

    _type=FieldProperty(str, if_missing='bike')

    def move(self):
        return 'cycling from {} to {}'.format(self.origin, self.destination)


Bus(origin='Rome', destination='London', passengers_count=20))
Bus(origin='Turin', destination='London', passengers_count=20))
AirBus(origin='Turin', destination='London', passengers_count=60, wings_count=3))
Bike(origin='Newcastle', destination='London'))
session.flush()
session.clear()

print(Transport.query.find().count())  # 4
print(Transport.query.find({'_type': 'bus'}).count())  # 2
print(Transport.query.find({'_type': 'airbus'}).count()) # 1

However I have also added next queries and would expect this to produce 3 and 1:

print(Bus.query.find().count())  # expected 3, got 4
print(AirBus.query.find().count())  # expected 1, got 4

but I get 4 and 4.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions