【发布时间】: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