【问题标题】:Using querysets properly正确使用查询集
【发布时间】:2012-04-28 17:32:19
【问题描述】:

我很确定使用查询集可以更有效地完成以下代码。我只是不知道怎么做。有什么建议么?这是我的代码:

orders = Order.objects.filter(contact=contact)
for order in orders:
    for item in order.orderitem_set.all():
        if cartitem.product_id == item.product_id:
            return True
return False

非常感谢, 托马斯

【问题讨论】:

    标签: django satchmo


    【解决方案1】:

    检查exists()lookups spanning relationships

    Order.objects.filter(contact=contact, 
                         order_item__product=cartitem.product_id).exists()
    

    【讨论】:

    • 谢谢好的!这就是我最终需要的:Order.objects.filter(contact=contact, orderitem__product=cartitem.product_id).exists() 我不确定为什么 product_id 必须成为产品,但无论如何现在可以了。
    • @user1294974 已修复。不知道为什么_id 不起作用,它通常应该用于 FK。但是是的,product 总是有效且代码更短。
    • @user1294974 欢迎来到 Stack Overflow!现在您已经通过 okm 的回答解决了问题,请务必使用绿色复选标记将其标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2019-04-04
    • 2021-11-26
    相关资源
    最近更新 更多