[英]Django refresh_from_db for ForeignKey
Is there a way to use refresh_from_db and automatically propagate it on ForeignKey ? 有没有办法使用refresh_from_db并自动在ForeignKey上传播它?
model.py: model.py:
class TestItemModel(models.Model):
value = models.IntegerField(default=0)
relies_on_item = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True )
shell: 贝壳:
>>> end_product = TestItemModel(value=1)
>>> end_product.save()
>>> container_product = TestItemModel(value=10,relies_on_item=end_product)
>>> container_product.save()
>>> end_product.pk
12
>>> end_product_for_update=TestItemModel.objects.get(pk=12)
>>> end_product_for_update.value = 4
>>> end_product_for_update.save()
>>> container_product.relies_on_item.value
1
>>> container_product.refresh_from_db()
>>> container_product.relies_on_item.value
1
The value returned at this point is still the initial one. 此时返回的值仍然是初始值。 Is there an option to make refresh_from_db automatically cascade on elements referenced by ForeignKey?
有没有选项让refresh_from_db自动级联在ForeignKey引用的元素上?
It is possible to do it by explicitly using refresh_from_db on the referenced item - shown below. 可以通过在引用的项目上显式使用refresh_from_db来实现它 - 如下所示。 But I would like to only have to do refresh_from_db on container_product itself.
但我想只需要在container_product本身上执行refresh_from_db。
shell (continued): 贝壳(续):
>>> container_product.relies_on_item.refresh_from_db()
>>> container_product.relies_on_item.value
4
AFAIK In django, Till now refresh_from_db
will not update data for relational fields.It only check whether relation is removed or not. AFAIK在django中,直到现在
refresh_from_db
不会更新关系字段的数据。它只检查关系是否被删除。 But you can do like (as you did). 但你可以这样做(就像你一样)。
for i in container_product._meta.concrete_fields:
if i.is_relation:
getattr(container_product, i.name).refresh_from_db()
OR override refresh_from_db
或覆盖
refresh_from_db
class Mymodel(models.Model):
def refresh_from_db(self, using=None, fields=None):
super(Mymodel, self).refresh_from_db(using=None, fields=None)
for i in self._meta.concrete_fields:
if i.is_relation and getattr(self, i.name):
getattr(self, i.name).refresh_from_db()
另一种解决方案是在不使用refresh_from_db
情况下从DB再次检索实例。
instance = MyModel.objects.get(pk=pk)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.