Hey everyone,

I did a little more digging and came up with a solution by extending
the default manager to add a new function 'get_orphans'.  When passed a
M2M non-symmetrical field, it will do a query and return a query set
containing all items which have no parent - ie. any item that does not
appear as an id in the 'to_*_id' field in the M2M relation db.  Below
is the manager code:

from django.db import connection, backend, models
from django.core.exceptions import ObjectDoesNotExist
import sys

class HierarchyManager(models.Manager):
  def get_orphans(self, field_name, exclude_list=None):

    reln = self.model._meta.get_field(field_name)
    to_model_type = reln.rel.to
    id_field = backend.quote_name('id')
    model_table = backend.quote_name(to_model_type._meta.db_table)
    join_table = backend.quote_name(reln.m2m_db_table())
    #from_field = backend.quote_name(reln.m2m_column_name())
    to_field = backend.quote_name(reln.m2m_reverse_name())

    query = """
        SELECT %s.%s FROM %s
        LEFT JOIN %s ON
        %s.%s = %s.%s
        WHERE
        %s.%s IS NULL""" % (
          model_table, id_field, model_table,
          join_table,
          model_table, id_field, join_table, to_field,
          join_table, to_field, )
    if exclude_list:
      query += """
        AND NOT %s.%s IN (%s)
        """ % ( model_table, id_field, ",".join([str(item) for item in
exclude_list]) )

    cursor = connection.cursor()
    cursor.execute(query)

    orphan_ids = [item[0] for item in cursor.fetchall()]
    return self.filter(id__in = orphan_ids)

This seems to be working quite well, and stays generic enough to use
for any M2M non-symmetrical field for a given model.  Any thoughts,
comments, criticisms?

Thanks,
Christian


--~--~---------~--~----~------------~-------~--~----~
 You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to