Note that there are some explanatory texts on larger screens.

plurals
  1. POEfficiently search through a tree of ForeignKeys in Django
    primarykey
    data
    text
    <p>I have a tree like structure created out of models using ForeignKey linkages. As an example:</p> <pre><code>Model Person: name = CharField Model Book: name = CharField author = FK(Person) Model Movie: name = CharField director = FK(Person) Model Album: name = CharField director = FK(Person) Model Chapter: name = CharField book = FK(Book) Model Scene: name = CharField movie = FK(Movie) Model Song: name = CharField album = FK(Album) </code></pre> <p>The caveat here is the real structure is both deeper and broader, and a node might have multiple non-FK fields (ie not just 'name').</p> <p>What I'd like to do is have a search function such that there is a string supplied which will return any Person that either matches a Person object itself, or a field in any of the child nodes. IOW, if "beat it" is the string, and the name of a song associated with an album associated w/ the person matches, the person will be returned.</p> <p>What I've done so far is the following:</p> <p>For any leaf node, have a Manager object w/ a search method which does something like: </p> <pre><code>return Song.objects.filter(name__icontains=search_string) </code></pre> <p>Then for the root node (Person) and any interior nodes, there is also a Manager object w/ a search() method which looks something like: </p> <pre><code>class AlbumManager(models.Model): def search(self, search_string): from_songs = Album.objects.filter(song__in=Song.objects.search(search_string)) return Album.objects.filter(name__icontains=search_string)|from_songs </code></pre> <p>As you might imagine, once you get to the root node, this unleashes a massive number of queries and is really inefficient. I'd be pretty surprised if there wasn't a better way to do this ... one idea is to just have one search() method at the top of the tree that manually searches through everything, but a) that seems very messy (albeit probably more efficient) and b) it would be nice to be able to search individual nodes arbitrarily.</p> <p>So with all of this said, what would be a more efficient method of getting where I want to be instead of my bonehead method here? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload