已解决如何使用Django自定义保存方法访问数据库对象?

问题描述 投票:0回答:1

我必须检查django模型的保存方法是用于创建新对象还是对其进行更新,因为如果更新,我必须从父对象更新子对象的状态。

class Categoria(Entidad):

  ESTADO = (("Activo", "Activo"), ("Inactivo", "Inactivo"))
  estado = models.CharField(verbose_name=_("Estado"), max_length=20, choices=ESTADO, default=1)
  categoria_padre = models.ForeignKey('self', verbose_name=_("Categoría Padre"), related_name='parent_category', related_query_name='child_category', null=True, blank=True, on_delete=models.CASCADE)

  def save(self, *args, **kwargs):

    from django.db import connection

    # first option does not work because i can access to django model manager
    old = self.objects.get(id=self.id)

    # second option throughs 500 error when create new objects
    cursor = connection.cursor()
    response = cursor.execute("SELECT * FROM cms_categoria WHERE id = '" + str(self.id) + "'")
    set = response.fetchall()
    connection.commit()
    cursor.close()
    connection.close()

第二个选项适用于本地开发,但当使用postgres将其推送到heroku时无效。

解决

if not self.pk:
  super(Categoria, self).save(*args, **kwargs)
else:
  old = Categoria.objects.get(id=self.pk)
  if old.estado != self.estado:
    children = Categoria.objects.filter(categoria_padre__id=self.pk)
    for child in children:
                child.updateChildrenStatus(self.estado)

    super(Categoria, self).save(*args, **kwargs)

有人可以帮我吗?谢谢,问候。

django database postgresql heroku
1个回答
0
投票

据我所知,您应该能够显着简化save()方法,无需导入连接和使用游标。

如果在save方法中,您需要检查实例是否已存在于数据库中,则可以执行以下操作:

def save(self, *args, **kwargs):
    if self.pk:
        # update your child objects here if it has been updated
        pass
    return super.save(*args, **kwargs)

这是因为如果在数据库(即新实例)中创建对象,则在调用super().save(*args, **kwargs)之前不会为其分配主键。如果存在主键,则说明它正在更新而不是创建。

© www.soinside.com 2019 - 2024. All rights reserved.