我有以下型号:
def Order(models.Model):
receiver = models.ForeignKey(Receiver)
warehouse = models.ForeignKey(Warehouse)
def Receiver(models.Model):
user = models.ForeignKey(User) #this is not made one to one because user can have more than one receiver
name = ...
zipcode = ...
def Warehouse(models.Model):
city = ...
street = ...
我想选择与request.User对象相关的所有Warehouse
条目。我现在能做到这一点的唯一方法是:
orders = Order.objects.filter(receiver__user=request.User)
# here i set orders warehouse ids to list called ids
user_warehouses = Warehouse.objects.filter(pk__in=ids)
但我有一种强烈的感觉,我正在发明轮子。有没有更简单的Django方式呢?
答案 0 :(得分:0)
Warehouse.objects.filter(order__receiver__user=request.user)
你可以向后遍历关系(“反向查找”)并使用双下划线语法遍历多个级别
https://docs.djangoproject.com/en/1.8/topics/db/queries/#lookups-that-span-relationships