On Apr 3, 11:45 am, Adam Dziendziel <[EMAIL PROTECTED]> wrote:
>
> Then, I set a primary key indirectly:
>
> translation = CategoryTranslation()
> translation.category = session.query(Category).filter(....).one()
> translation.language = session.query(Language).filter(....).one()
>
> 1. How to check whether the primary key is set? I cannot simply check
> if every column of class_mapper(CategoryTranslation).primary_key is
> set, because these field are empty until I save  save the object.

i would rephrase this question as, "how to check if a required foreign
key constraint will be fulfilled based on the interactions of an
instance with related instances".   an entirely generic way might be:

from sqlalchemy.orm import sync
def manytoones_are_set(instance):
    for prop in object_mapper(instance).iterate_properties:
        if getattr(prop, 'direction', None) == sync.MANYTOONE:
            if not getattr(instance, prop.key):
                return False
    else:
        return True

> 2. How to retrieve that key? I would like to check if the record
> already exists.

This is a great question for me because coming up with the function
for this revealed a terrific refactoring I think I'm going to try.
This function will work for single-valued primary and foreign keys.
For a multiple valued pk/fk, there is a more complicated function that
can work here, but my refactoring will involve making the "local_side"
and "remote_side" collections on PropertyLoader ordered, so that
questions like these can be answered more easily:

def manytoone_columns(instance):
    mapper = object_mapper(instance)
    for prop in mapper.iterate_properties:
        if getattr(prop, 'direction', None) == sync.MANYTOONE:
            local, remote = list(prop.local_side)[0],
list(prop.remote_side)[0]
            value = getattr(instance, prop.key)
            remote_value = getattr(value, remote.key)
            yield (local, remote_value)


def apparent_primary_key(instance):
    mapper = object_mapper(instance)
    values = dict(list(manytoone_columns(instance)))
    for col in mapper.primary_key:
        if col in values:
            yield values[col]
        else:
            yield getattr(instance, col.key)

print list(apparent_primary_key(some_instance))


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" 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/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to