Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
模型django选择两个值中的一个_Django - Fatal编程技术网

模型django选择两个值中的一个

模型django选择两个值中的一个,django,Django,我需要选择其中一个,但不能同时为空。可能吗 location = models.ForeignKey('Location', help_text="Enter inventory location", null=True, blank=True) assigned = models.ForeignKey(User, blank=True, null=True) 您可以在模型中重写方法来处理此问题 def saveself,*args,**kwargs: 如果不是自定位且不是自分

我需要选择其中一个,但不能同时为空。可能吗

location     = models.ForeignKey('Location', help_text="Enter inventory location", null=True, blank=True)
assigned     = models.ForeignKey(User, blank=True, null=True)
您可以在模型中重写方法来处理此问题

def saveself,*args,**kwargs: 如果不是自定位且不是自分配: 警告用户该问题 其他: 超级,自我保存*args,**kwargs
您可以在clean方法中验证模型。如果模型无效,可以引发验证错误:

def clean(self):
    if not self.location and not self.assigned:
        raise ValidationError('Either location or assigned should be non-blank')
有关clean方法的更多信息,请参阅Django文档:

我想到了两种解决方案。重写save方法以检查此项。2.向一个或两个字段添加默认选项。离题问题:当引发ValidationError时会发生什么?怎么抓住它?接下来会发生什么?代码从何处继续执行?在哪里可以访问引发的文本错误?@MihaiZamfir在Django管理员中,ValidationError将导致错误消息。如果您将模型保存在admin之外,您应该自己捕获异常。它只是一个常规的Python异常,所以它的工作原理与常规的Python异常类似,您可以在Python文档中阅读更多关于它的内容。