python - 创建模型后如何运行方法?

标签 python django

目前,我正在使用信号在创建新子网时触发 IP 的创建。

但是 #django 中的一些人说更好的方法是创建一个自定义 save() 或让 form 处理它(如果有 ForeingKey)。

还有比使用信号更合适的解决方案吗?如果是这样,有人可以给我看一个代码示例吗?

我的子网模型(models.py):

class Subnet(models.Model):
    network_address = models.IPAddressField()
    subnet_prefix = models.ForeignKey(SubnetPrefix)

我的 IP 地址模型 (models.py):

class IPAddress(models.Model):
    subnet = models.ForeignKey(Subnet)
    ip_address = models.IPAddressField()
    hostname = models.CharField(max_length=255, null=True, blank=True)

我的信号(models.py):

def subnet_post_save(sender, instance, created, *args, **kwargs):
        # If this is a new object create ip_addresses in IPAddress table
        if created:
            create_ip_addresses(instance)

最佳答案

您必须重写save方法:

class Subnet(models.Model):
    network_address = models.IPAddressField()
    subnet_prefix = models.ForeignKey(SubnetPrefix)

    def save(self, *args, **kwargs):
        created = not self.pk
        super(Subnet, self).save(*args, **kwargs)
        if created:
            create_ip_addresses(self)

关于python - 创建模型后如何运行方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20693050/

相关文章:

python - Django 未使用的方法参数

python - django:实例化 AdminSite 更改未反射(reflect)出来

python - 将 numpy 数组与 scipy odeint 一起使用

python - 用于 Python 开发的 Sublime 与 PyCharm

python - 根据 Pandas 中另一列的索引从一列获取数据

python - Pandas 中的日期格式顺序

python - 在 Python 的 openpyxl 中用颜色填充行 Excel

python - Django应用程序布局: Internationalization

python - 错误: 'NameError: name ' terms_and_conditions' is not defined' when it is

django - 在Django中建立资讯主页