adewes / blitzdb

Blitz is a document-oriented database for Python that is backend-agnostic. It comes with a flat-file database for JSON documents and provides MongoDB-like querying capabilities.
http://blitzdb.readthedocs.org
MIT License
330 stars 37 forks source link

How do you delete/retrieve a sub-document from a document? #21

Closed grplyler closed 10 years ago

grplyler commented 10 years ago

I have a Document class: project, and another class task. Now each project contains a list of tasks, how would i delete a task from a project? See code here: https://gist.github.com/grplyler/c3f64db0c8ea817a8053

adewes commented 10 years ago

Thanks for your question Ryan, I can think of two ways to solve this problem:

-Embed the task data directly in the project document (without creating a new class):

class Project(Document):

    pass

project = Project({'tasks' : [{'name' : 'task 1',...},{'name' : 'task 2'}]})

#You can create indices for effective querying of the tasks:
backend.create_index(Project,'tasks.name')

-Create a task class and use a foreign key to the project document class:

class Project(Document):
    pass

class Task(Document):
    pass

#Create and save a project
my_project = Project(...)
backend.save(my_project)
backend.commit()

#Create a task with a project reference
my_task = Task({'project' : my_project})
backend.save(my_task) #will store a reference to the project document in the task document

#Get all tasks for a given project:

project_tasks = backend.filter(Task,{'project' : my_project})

Let me know if that answers your question, will do my best to help you to solve your problem.

grplyler commented 10 years ago

Hi adewes, For now i think i'll go with the first option, and maybe later use the second. Thanks for your help. starred