【问题标题】:Related Manager is empty in one direction but not the other相关经理在一个方向为空,但在另一个方向上没有
【发布时间】:2023-04-01 09:21:01
【问题描述】:

我在 Django 模型上有一个方法,在该方法中我通过将 self 传递给 get_or_create 来创建一个新的相关实例:

def increment_or_create_item(self, product)
    item, created = Item.objects.get_or_create(cart=self, product=product)

奇怪的是,在调用上述行后,该项目不会直接显示在 self.items.all() 中。 这有效:

assert self == item.cart # does not raise

但这引发了:

assert self.items.all() == item.cart.items.all() #does raise
assert self.items.count() == item.cart.items.count() #does raise

self.items.all() 返回一个空的查询集,而item.cart.items.all() 返回正确的填充查询集。

我尝试拨打self.refresh_from_db(),但没有成功。

模型真的很大,所以我不会在这里发布它们,但我想重要的部分在这里:

class CartItem(Model):
    class Meta:
        unique_together = ['product', 'cart']

    num_units = models.PositiveIntegerField(default=1)

    product = models.ForeignKey(
        'boxes.Product',
        on_delete=models.CASCADE,
    )

    cart = models.ForeignKey(
        Cart,
        related_name='items',
        on_delete=models.CASCADE)

这怎么可能? 谢谢!

【问题讨论】:

  • Django 版本为 2.0.6
  • 你确定查询集是空的吗? Django的QuerySet类没有定义__eq__方法,所以比较是根据对象标识进行的;因为这两个查询集是独立的对象,所以它们不会相等。
  • 是的,我也打印了它们,可以清楚地看到其中一个是空的。实际上,我是通过比较 .count() 来发现这一点的。
  • 可以展示模型吗?
  • 感谢您的帮助,我发布了一个摘录,有很多方法但应该与此无关。

标签: python django python-3.x postgresql


【解决方案1】:

我最终用调试器深入研究了这个问题,突然间不对称消失了,item.cart.items.all() 实际上并没有反映数据库的状态。

似乎相关管理器中有某种​​缓存或刷新逻辑妨碍了我,我仍然不明白。

我最终重新调用了 CartItem 模型,而不是通过相关的管理器,一切都很好。

CartItem.objects.filter(cart=self).all()

而不是上面的

self.items.all()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多