Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy mixin, foreignkey and relation

I am having trouble creating a simple mixin that i plan to use on a bunch of sqlalchemy declarative classes. The basic idea is I want to have a create/modify time stamp and a create/modify user stored on multiple tables. The mixin is in its own file (global_mixins.py) and the class is imported in each model file that needs the mixin. When I run an import of data i get the error below the code.

class TimeUserMixin(object):
    create_time = Column(DateTime,default=datetime.datetime.now,nullable=False)
    modify_time = Column(DateTime,default=datetime.datetime.now,
                    onupdate=datetime.datetime.now,nullable=False)

    @declared_attr
    def create_user_id(cls):
        return Column(Integer,ForeignKey('tg_user.user_id'),
                      default=cls.get_user_id,nullable=False)

    @declared_attr
    def modify_user_id(cls):
        return Column(Integer,ForeignKey('tg_user.user_id'),
                      default=cls.get_user_id,onupdate=cls.get_user_id,nullable=False)

    @declared_attr
    def create_user(cls):
        return relation('User',primaryjoin='%s.create_user_id == User.user_id'%cls.__name__)

    @declared_attr
    def modify_user(cls):
        return relation('User',primaryjoin='%s.modify_user_id == User.user_id'%cls.__name__)

    @classmethod
    def get_user_id(cls):
        #will eventually return user id if logged in or a generic system user.
        return 1

Error(DETAIL:  Key (create_user_id)=(1) is not present in table "tg_user".)
like image 919
Ominus Avatar asked Feb 07 '12 20:02

Ominus


1 Answers

This was an order of operations issue. I wasn't reading the output closely. Basically i was trying to assign a user before any users had been created.

like image 130
Ominus Avatar answered Sep 29 '22 22:09

Ominus