It's maybe not as rigorous as the explicitly _meta-based approach
noted by Russ McGee, but I use straight introspection combined with a
knowledge of naming conventions, as follows:

# This function looks only at passed in object, not its derived
subobjects
# If you want items from the most derived class or whatever, get that
object first
# and then call this function on it.

def getRelatedManagerNamesAndObjects(object,namePrefix=None): #
returns a list of name-value pairs
    if namePrefix == None:
        namePrefix = ''
    namesAndValues = []
    for name in dir(object):
        if not name.startswith(namePrefix):
            continue
        try:
            value = getattr(object,name)
        except:
            continue
        typeStr = str(type(value))
        if typeStr.find('RelatedManager') != -1:
            namesAndValues.append((name,value))
    return namesAndValues

It doesn't find 121 relationships, only m21 (FK) and m2m, but that's
what I want to find.  I use a similar introspection method to find 121
relationships, which for me all result from multi-level multi-table
inheritance.  So far both methods have worked fine for me.  They may
seem a little inefficient but I don't do them that often and I assume
that the resources they use are nothing compared to the joins that are
needed to get the actual data I'm looking for (i.e. queries made on
the returned related managers).

-- John

On Dec 27, 9:01 pm, Daniel Kaplun <m...@dvir.us> wrote:
> How do I get all models with FKs, M2Ms, or 121s pointing to a given
> model?
>
> I am using djcelery. I have a BakedModel with a FK to TaskMeta, which
> is the model that stores task status (I only care whether it is
> complete). I want to generate a query set that will return all
> instances of a given model where all deep references to and from the
> instance that are TaskMeta instances have status=SUCCESS. Currently, I
> am able to perform said operation for all relations from a given
> model, but the other way -- to a given 
> model.http://paste.pocoo.org/show/526681/

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

Reply via email to