Can you merge querysets or objects?

43 views
Skip to first unread message

Stephen McCamy

unread,
May 1, 2020, 2:46:25 PM5/1/20
to MongoEngine Users
Hello,  I am trying to figure out a way to combined data from two collections into one object I can reference in code. I have manually created a dictionary and just added the data to it.  This works but I want to see if there is a better way.  End goal is the have a many to many type relationship where I can show the item groups that an item belongs to as well as the items that belong to an item group.  I don't know if a lookup would accomplish this or if there is a better way to approach it on the collection end?

class Items(Document):
    item
= StringField(required=True)
    tags
= ListField()


class ItemGroups(Document):
    name
= StringField(required=True)
    items
= ListField(ReferenceField(Items, reverse_delete_rule=PULL))

 
item
= Items.objects(item="item1").first()
itemgroups
= ItemGroups.objects(items=item).all()


if item:
   
if itemgroups:
        groupslist
= []
       
for group in itemgroups:
            groupslist
.append(group.name)
        item_dict
= item.to_mongo().to_dict()
        item_dict
.update({"item_groups": groupslist})






Reply all
Reply to author
Forward
0 new messages