Djang强制一对多关系

2024-10-01 17:26:08 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个模型OwnedCar(汽车是拥有的,不是由乘客共享的)和一个模型Passenger(乘客包括公共汽车的司机)。这些模型可以通过DRF和管理接口读/写。你知道吗

我如何强制每辆车至少有一名乘客,可能有几个乘客(强制一对多关系)?在创建模型之前,我必须如何/在何处实施验证?你知道吗


Tags: 模型关系汽车drf司机乘客passenger每辆车
1条回答
网友
1楼 · 发布于 2024-10-01 17:26:08

Django docs你应该使用型号.清洁()

This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field

你的代码应该是这样的

class Car(models.Model):
    ...
    def clean(self):
        if self.passangers.count() == 0:
            raise ValidationError(_('Car cannot be empty')) 
        if self.passangers.filter(type='Driver').count() == 0:
            raise ValidationError(_('You need at least one driver in the car.'))

相关问题 更多 >

    热门问题