【问题标题】:Django UniqueConstraintDjango 唯一约束
【发布时间】:2019-09-25 04:51:49
【问题描述】:

上下文

我有模型AppVersion、App 和DeployApp。在AppVersion 模型中,用户可以将APK 文件上传到文件系统。我正在使用pre_save 信号来防止为特定的App 上传具有相同version_code 的APK 文件,如下所示:

@receiver(pre_save, sender=AppVersion)
def prevent_duplicate_version_code(sender, instance, **kwargs):
    qs = AppVersion.objects.filter(app_uuid=instance.app_uuid, version_code=instance.version_code)
    if qs.exists():
        raise FileExistsError("Version code has to be unique for a specific app")

这个信号做我想要的,除了当我试图在桥表DeployApp中创建一个对象时它也会引发错误。

型号

# models.py

class App(models.Model):
    app_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)
    app_name = models.CharField(max_length=100)


class AppVersion(models.Model):
    app_version_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)
    app_uuid = models.ForeignKey(App, on_delete=models.CASCADE, related_name='app_versions')
    app_version_name = models.CharField(max_length=100)
    version_code = models.IntegerField(blank=True, null=True, editable=False)
    source = models.FileField(upload_to=get_app_path, storage=AppVersionSystemStorage()) 


class DeployApp(models.Model):
    deploy_app_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)
    app_version = models.ForeignKey(AppVersion, on_delete=models.CASCADE)
    device_group = models.ForeignKey(DeviceGroup, on_delete=models.CASCADE)
    release_date = UnixDateTimeField()

我的猜测是,当创建DeployApp 的对象时,相关的AppVersion 也会被保存,因此会调用pre_save 信号并引发异常。

我还尝试为AppVersion 模型覆盖save() 方法,但结果相同。

如何确保仅在创建新的 AppVersion 实例时发生异常,而在添加或编辑 DeployApp 实例时不会发生异常?

【问题讨论】:

  • 为什么不docs.djangoproject.com/en/2.2/ref/models/options/…unique_together unique_together = ['app_uuid', 'app_version_name']?
  • 不,如果相关模型已经存在并且您所做的只是创建一个DeployApp 对象,则不会保存相关模型。那是不可能的。您的代码中必须有一些内容明确保存了 AppVersion 对象。
  • @BearBrown unique_together 很快就会过时。看看UniqueConstraint

标签: python django unique-constraint


【解决方案1】:

感谢 Bear Brown 的建议,解决了这个问题。我删除了信号并将UniqueConstraint 添加到AppVersion 模型中,如下所示:

class Meta:
    db_table = 'app_version'
    constraints = [
        models.UniqueConstraint(fields=['app_uuid', 'version_code'], name='unique appversion')
    ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    • 2021-08-05
    • 2021-04-01
    • 2021-09-30
    相关资源
    最近更新 更多