Django的UniqueConstraint [英] Django UniqueConstraint
问题描述
我有以下模型: AppVersion
, App
& DeployApp
.在 AppVersion
模型中,用户可以将APK文件上传到文件系统.我正在使用 pre_save
信号来阻止为特定的 App
上载具有相同 version_code
的APK文件,如下所示:
I have the models AppVersion
, App
& DeployApp
. In the AppVersion
model users can upload APK files to the filesystem. I am using a pre_save
signal to prevent uploading APK files with the same version_code
for a specific App
like this:
@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
中创建对象时还会引发错误.
This signal does what I want, except it also raises the error when I am trying to create an object in the bridge-table 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
信号并引发例外.
My guess is that when creating an object of DeployApp
the related AppVersion
is also saved and thus the pre_save
signal is called and raises the Exception.
我还尝试为 AppVersion
模型覆盖 save()
方法,但结果相同.
I also tried to override the save()
method for the AppVersion
model but the results are the same.
如何确保仅在创建新的 AppVersion
实例时发生该异常,而在添加或编辑 DeployApp
实例时该异常不会发生?
How do I make sure that the Exception only happens upon creating a new AppVersion
instance and does not happen when adding or editing a DeployApp
instance?
推荐答案
感谢贝尔·布朗(Bear Brown)的建议,解决了该问题.我删除了信号,然后将 UniqueConstraint
添加到 AppVersion
模型中,如下所示:
Solved it thanks to Bear Brown his suggestion. I removed the signal and added UniqueConstraint
to the AppVersion
model like this:
class Meta:
db_table = 'app_version'
constraints = [
models.UniqueConstraint(fields=['app_uuid', 'version_code'], name='unique appversion')
]
这篇关于Django的UniqueConstraint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!