mongoengine icon indicating copy to clipboard operation
mongoengine copied to clipboard

Add SetField (like ListField but returns a Python set)

Open PixyMisa opened this issue 12 years ago • 5 comments

Simple feature request - it would be quite helpful to my application to have a SetField type that accepts and returns a Python set instead of a list.

PixyMisa avatar Mar 07 '12 09:03 PixyMisa

second this. List doesn't have uniqueness checking...

tonyxiao avatar Jul 10 '12 04:07 tonyxiao

third that!

huangkuan avatar Apr 03 '13 16:04 huangkuan

How about this?

class SetField(ListField):
    """ Set field.

        Extends ListField, so that's how it's represented in Mongo.
    """
    def __set__(self, instance, value):
        return super().__set__(instance, set(value))

    def to_mongo(self, value):
        return super().to_mongo(list(value))

    def to_python(self, value):
        return set(super().to_python(value))

    def validate(self, value):
        if not isinstance(value, set):
            self.error('Only sets may be used.')

moorchegue avatar Sep 05 '13 21:09 moorchegue

+1

prymitive avatar Mar 29 '14 13:03 prymitive

I tried following code:

class SetField(ListField):
    """ Set field.

        Extends ListField, so that's how it's represented in Mongo.
    """

    def __set__(self, instance, value):
        super(SetField, self).__set__(instance, set(value) if value is not None else None)

    def to_mongo(self, value):
        return super(SetField, self).to_mongo(list(value))

    def to_python(self, value):
        return set(super(SetField, self).to_python(value))

    def validate(self, value):
        if not isinstance(value, set):
            self.error('Only sets may be used.')
        super(SetField, self).validate(list(value))

But this is giving me BaseList instance not set instance. I am using version 0.10.5

knoxxs avatar Feb 27 '16 16:02 knoxxs