我正在寻找在Django模型中实现这种机制的最有效方法。 我们假设有两种非常简单的模型:
class FKModel(models.Model):
value = BooleanField()
class AModel(models.Model):
fk = models.ForeignKey(FKModel)
a_value = models.CharField(max_length=150)
def clean(self, *args, **kwargs):
# the line below is incorrect
if not self.fk.value: # <--- how to do this in a proper way?
raise ValidationError('FKModel value is False')
super(AModel, self).clean(*args, **kwargs)
def save(self, *args, **kwargs):
self.full_clean()
super(AModel, self).save(*args, **kwargs)
我知道,我可以做类似FKModel.objects.all()/.get()
的事情,但是我认为这不是最好的解决方案(因为它需要对数据库的额外请求)。
答案 0 :(得分:0)
我不确定您尝试在clean()
方法中做什么,但是我认为您正在尝试约束外键的非null条件。默认情况下,所有字段都不都是null约束的,如果您想让字段接受null,则必须设置null=False
和blank=False
:
class AModel(models.Model):
fk = models.ForeignKey(FKModel, null=True, blank=True)
a_value = models.CharField(max_length=150)
如果要手动限制字段的非空条件,则应这样操作:
class FKModel(models.Model):
value = BooleanField()
class AModel(models.Model):
fk = models.ForeignKey(FKModel)
a_value = models.CharField(max_length=150)
def clean(self, *args, **kwargs):
# the line below is correct
if self.fk is None: # <--- this is the proper way?
raise ValidationError('FKModel value is False')
super(AModel, self).clean(*args, **kwargs)
def save(self, *args, **kwargs):
self.full_clean()
super(AModel, self).save(*args, **kwargs)
要检索数据库记录及其相关记录,请使用 prefetch_related ,然后在一个数据库命中项中获取记录及其相关记录:
AModel.objects.all().prefetch_related('fk')