gpt4 book ai didi

django - 使用两个可选但一个必需的外键创建模型

转载 作者:行者123 更新时间:2023-12-03 16:07:42 25 4
gpt4 key购买 nike

我的问题是我有一个模型,可以使用两个外键之一来说明它是哪种模型。我希望它至少要拿一个,但不能两个都拿。我可以让它仍然是一个模型还是应该将其分为两种类型。这是代码:

class Inspection(models.Model):
InspectionID = models.AutoField(primary_key=True, unique=True)
GroupID = models.ForeignKey('PartGroup', on_delete=models.CASCADE, null=True, unique=True)
SiteID = models.ForeignKey('Site', on_delete=models.CASCADE, null=True, unique=True)

@classmethod
def create(cls, groupid, siteid):
inspection = cls(GroupID = groupid, SiteID = siteid)
return inspection

def __str__(self):
return str(self.InspectionID)

class InspectionReport(models.Model):
ReportID = models.AutoField(primary_key=True, unique=True)
InspectionID = models.ForeignKey('Inspection', on_delete=models.CASCADE, null=True)
Date = models.DateField(auto_now=False, auto_now_add=False, null=True)
Comment = models.CharField(max_length=255, blank=True)
Signature = models.CharField(max_length=255, blank=True)

问题是 Inspection模型。这应该链接到组或站点,但不能同时链接到两者。目前,通过此设置,它同时需要两者。

我宁愿不必将其分为两个几乎相同的模型 GroupInspectionSiteInspection,因此将其保持为一个模型的任何解决方案都是理想的。

最佳答案

我建议您对Django way进行此类验证

通过覆盖Django模型的clean方法

class Inspection(models.Model):
...

def clean(self):
if <<<your condition>>>:
raise ValidationError({
'<<<field_name>>>': _('Reason for validation error...etc'),
})
...
...


Note, however, that like Model.full_clean(), a model’s clean() method is not invoked when you call your model’s save() method. it needs to be called manually to validate model's data, or you can override model's save method to make it always call the clean() method before triggering the Model class save method



Another solution that might help is using GenericRelations, in order to provide a polymorphic field that relates with more than one table, but it can be the case if these tables/objects can be used interchangeably in the system design from the first place.

关于django - 使用两个可选但一个必需的外键创建模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59643184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com