Adding and updating ListField with Mongoengine

Using Mongoengine and trying to create a tag cloud. For each element, I would like to add one or more tags. It uses something similar, like tags (below each question asked).

After searching and reading many posts here, I still cannot correctly add new entries to the ListField or how to replace them.

class Item(Document): tags = ListField(StringField(max_length=300)) 

I try to click one or more new tags using the form and collect the published results. In my view.py, I have the following check:

 if 'tags' in request.POST and request.POST['tags'] <> '': for Tag in request.POST.getlist('tags'): ItemData.update(push__tags__S__tags=Tag) 

When you try to click it, it fails:

ValidationError (Profile: 5185505b73ea128e878f4e82) (Only lists and tuples can be used in the list box: ['tags'])

Obviously, I am using the wrong type, but I have lost how to solve this problem. The strange thing is that for some reason the data is added to the record, though .. (a "test" and an updated browser are posted)

"tags": ["test", "test"]}

Is it possible to show a small example of how to deal with a published string (from an HTML form) and insert it correctly in a ListField (and how to replace them).

Thanks!

+4
source share
1 answer

You do not need the positioning operator $ , which equates to __S__ in mongoengine, since you are not replacing / updating the position in the list.

As you probably don't want to repeat tags, you should use $ addToSet . You can do it in mongoengine like this:

 ItemData.update(add_to_set__tags=['tag1', 'tag2']) 

Passing to the add_to_set list automatically converts it to $addToSet using $each .

+6
source

Source: https://habr.com/ru/post/1481668/


All Articles