【问题标题】:How to access to database objects in django custom save method?如何在 django 自定义保存方法中访问数据库对象?
【发布时间】:2020-01-25 09:27:20
【问题描述】:

我必须检查 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。

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

【问题讨论】:

标签: django database postgresql heroku


【解决方案1】:

据我所知,您应该能够显着简化您的 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) 之前不会为其分配主键。如果主键存在,您就知道它正在更新,而不是创建。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多