danielrvt
danielrvt

Reputation: 10926

Mongokit validate dict inside list

How can I validate that my desc field is required and my category field is optional?

class Mydoc(Document):

    structure = {
        "name": unicode,
        "items": [{
             "category": int,
             "desc": unicode
        }]
    }

 required_fields = ["name", "items", "items.desc"] # Error: items has no attribute 
                                                   # desc, it is a list not a dict.

How can I validate the categories inside the list?

UPDATE

https://groups.google.com/forum/?fromgroups=#!topic/mongokit/GP5AgaMG6T4

Upvotes: 0

Views: 619

Answers (1)

Namlook
Namlook

Reputation: 181

The tricky point here is that we do not know how many items there are. Mongokit doesn't allow you to specify a nested object as required because it could potentially be very slow if you have many items.

So, in short, mongokit doesn't allow required_fields and default_values in nested objects.

However, Mongokit is very light and can be customized very easily if needed:

class MyDoc(Document):
    structure = {
        "name": unicode,
        "items": [{
             "category": int,
             "desc": unicode
        }]
    }

    def validate(self, *args, **kwargs):
        super(MyDoc, self).validate(*args, **kwars)
        for item in self["items"]:
            assert item["desc"], "desc is required: %s" % item

Upvotes: 2

Related Questions