I have an SQLAlchemy model, say Entity and this has a column, is_published. If I query this, say by id, I only want to return this if is_published is set to True. I think I can achieve using a filter. But in case there is a relationship and I am able to and require to access it like another_model_obj.entity and I only want this to give the corresponding entity object if the is_published for that instance is set to True. How should I do this? One solution would be wrap this around using an if block each time I use this. But I use this too many times and if I use it again, I will have to remember this detail. Is there any way I can automate this in SQLAlchemy, or is there any other better solution to this problem as a whole? Thank you
Add a comment |
2 Answers
It reads as if you would need a join:
session().query(AnotherModel).join(Entity).filter(Entity.is_published) 4 Comments
9000
IIRC you can even leave out the explicit
.join and write ...query(Entity, AnotherModel).filter(...).knitti
you could probably do this, but then AnotherModel instances will be part of the result set
adarsh
Of course for stuff in the model and service files I use something like this. For views, I abort with a 404. But in some inevitable template usage where I can't put a full blown query, what can I do?
knitti
I don't quite understand. If you need the query, do it. There's no reason not to do a join when the information is needed.
This question was asked many times here and still doesn't have a good answer. Here are possible solutions suggested by the author of SQLAlchemy. A more elaborate query class to exclude unpublished objects is provided in iktomi library. It works with SQLAlchemy 0.8.* branch only for now but should be ported to 0.9.* soon. See test cases for limitations (tests that fail are marked with @unittest.skip()) and usage examples.