简体   繁体   中英

Mandatory one to many relationship in Django

Suppose I've a model OwnedCar (cars are owned, not shared by passengers) and a model Passenger (passenger includes the driver of the bus). The models are read/write able via DRF and admin interface.

How can I enforce that each car has at least one passenger and potentially several passengers (mandatory one-to-many relationship)? How/where do I have to implement validation before a model is created?

From Django docs you should use Model.clean()

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

Your code should look something like this

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.'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM