I'm working on a pyramid traversal project and i want to run different query for retrieving the same resource base on its parent or so.
Say i have 3 resources: Customer, Store, Order. now both Customer and Store could have a list of Orders. So i define an OrderListResource as a resource and my view is like:
@view_config(context=resources.OrderListResource, renderer='json')
def view_order_list(context, request):
return {orders: context.retrieve_method()}
Now i wonder what is the best practice to retrieve data base on resource parent?
For example how OrderListResource should decide to retrieve orders by customer id or by store id. the logics should lie on the view or the resource itself?
Thanks.
Well, since you're using traversal, getting to the parent of your resource is very easy:
parent = context.__parent__
query = session.query(OrderList)
if isinstance(parent, CustomerResource):
query = query.filter(OrderList.customer_id == parent.id)
elif isinstance(parent, StoreResource):
query = query.filter(OrderList.store_id == parent.id)
If the parent you want to check may not be an immediate parent of your resource you can use pyramid.traversal.find_interface method.
Alternatively, if the logic differs a lot depending on whether the Order is contained within a Customer or Store, you may have two separate views using the containment
view predicate.
@view_config(context=resources.OrderListResource, containment=CustomerResource, renderer='json')
def view_order_list_for_customer(context, request):
return ...
@view_config(context=resources.OrderListResource, containment=StoreResource, renderer='json')
def view_order_list_for_store(context, request):
return ...