I’ve got
class Supplier(Model) :
pass
class Customer(Model) :
pass
class Dock(Model) :
pass
class SupplierDockAccess(Model) :
supplier = ForeignKey(Supplier)
dock = ForeignKey(Dock)
class SupplierCustomerAccess(Model):
supplier = ForeignKey(Supplier)
customer = ForeignKey(Customer)
I have an instance of Customer, and I’d like to get all Docks that the customer has access to. Customers have access to Suppliers via SupplierCustomerAccess, and Suppliers have access to Docks via SupplierDockAccess. I can do it like so:
# get the suppliers the customer has access to
supplier_customer_accesses = SupplierCustomerAccess.objects.filter(customer=customer)
suppliers = [s.supplier for s in supplier_customer_accesses]
# get the docks those suppliers have access to
supplier_dock_accesses = SupplierDockAccess.objects.filter(supplier__in=suppliers)
docks = [s.dock for s in supplier_dock_accesses]
… but then the resulting list of docks contains duplicates, and I really think it oughtta be possible to do it in one go. Anyone feel like demonstrating some mighty django-fu?
Easiest way I can think of to do this is a combination of
ManyToManyFields and a custom QuerySet/Manager.You should see only one or two hits to the database (depending on if you used
select_relatedwhen you got your customer), and your code is insanely clean: