How do I specify a relation in SQLAlchemy where one condition requires a column to be null?

foreign-key-relationship, python, sqlalchemy

Solution

Try using `and_` as `and` is not overloaded:

and_((Matter.id == WorkItem.matter_id), (WorkItem.line_item_id == None))

Problem

Not sure what the correct title for this question should be. I have the following schema: - Matters have a one-many relationship to WorkItems. - WorkItems have a one-one (or one-zero) relationship to LineItems. I am trying to create the following relation between Matters and WorkItems ``` Matter.unbilled_work_items = orm.relation(WorkItem, primaryjoin = (Matter.id == WorkItem.matter_id) and (WorkItem.line_item_id == None), foreign_keys = [WorkItem.matter_id, WorkItem.line_item_id], viewonly=True ) ``` This throws: ``` AttributeError: '_Null' object has no attribute 'table' ``` That seems to be saying that the second clause in the primaryjoin returns an object of type _Null, but it seems to be expecting something with a "table" attribute. This seems like it should be pretty straightforward to me, am I missing something obvious? Update The answer was to change the `primaryjoin` line to: ``` primaryjoin = "and_(Matter.id == WorkItem.matter_id, WorkItem.line_item_id == None)" ```

Original source