accepted_bids = Bid.objects.filter(shipment__user=u, status='acc').select_related('shipment')
completed_shipments = []
for b in accepted_bids:
completed_shipments.append(b.shipment)
vehicles_shipped = []
for s in completed_shipments:
vehicles_shipped.extend(s.items.all())
最后,我想要一份已发货的车辆清单。如果车辆已完成装运,则装运车辆。如果已接受出价,则已完成装运。
我不希望迭代查询集,从而在必要之前强制命中数据库......例如,是不是有办法从出价列表中获取所有关联的货件?
这是我模特的精简版:
class Shipment(Model):
user = ForeignKey(User, related_name='shipments')
class ShipmentItem(models.Model):
shipment = ForeignKey(Shipment, related_name='items')
class Meta:
abstract = True
class VehicleItem(ShipmentItem):
pass
class Bid(Model):
user = ForeignKey(User, related_name='bids')
shipment = ForeignKey(Shipment, related_name='bids')
答案 0 :(得分:1)
提供架构很重要。但这是一个猜测:
Vehicle.objects.filter(shipment__bid__status='acc', shipment__user=u)