Brian Hicks
Brian Hicks

Reputation: 6403

Creating a multi-model in Django

I'd like to create a directed graph in Django, but each node could be a separate model, with separate fields, etc.

Here's what I've got so far:

from bannergraph.apps.banners.models import *

class Node(models.Model):
    uuid = UUIDField(db_index=True, auto=True)

    class Meta:
        abstract = True

class FirstNode(Node):
    field_name = models.CharField(max_length=100)

    next_node = UUIDField()

class SecondNode(Node):
    is_something = models.BooleanField(default=False)

    first_choice = UUIDField()
    second_choice = UUIDField()

(obviously FirstNode and SecondNode are placeholders for the more domain-specific models, but hopefully you get the point.)

So what I'd like to do is query all the subclasses at once, returning all of the ones that match. I'm not quite sure how to do this efficiently.

Things I've tried:

  1. Iterating over the subclasses with queries - I don't like this, as it could get quite heavy with the number of queries.
  2. Making Node concrete. Apparently I have to still check for each subclass, which goes back to #1.

Things I've considered:

So, am I approaching this wrong, or forgetting about some neat feature of Django? I'd rather not use a schemaless DB if I don't have to (the Django admin is almost essential for this project). Any ideas?

Upvotes: 0

Views: 88

Answers (1)

Jay
Jay

Reputation: 2569

The InheritanceManager from django-model-utils is what you are looking for.

You can iterate over all your Nodes with:

nodes = Node.objects.filter(foo="bar").select_subclasses()
    for node in nodes:
        #logic

Upvotes: 1

Related Questions