Home > Mobile >  Django models foreign key validation
Django models foreign key validation

Time:10-23

I have the following Django models:

class Owner(models.Model):
    name = models.CharField(max_length=30)

class Dog(models.Model):
    name = models.CharField(max_length=30)
    owner = models.ForeignKey(Owner)


class GoForAWalk(models.Model):
    date = models.DateTimeField()
    location = models.CharField()

    owner = models.ForeignKey(Owner)
    dog = models.ForeignKey(Dog)

I want that a Owner can only GoForAWalk with one of his own Dog.

Currently any owner can go for a walk with any dog.

Would you restrict this via model validators or via some logic during the creation of a new GoForAWalk object?

Can anyone provide an example? I'm quite stuck.

Thanks a lot!

Cheers, Philipp

CodePudding user response:

GoForAWalk doesn't need an owner as it "comes with" a dog, so if the dog goes for a walk you already know with whom. Just remove owner from GoForAWalk. This will fix possible inconsistencies.

CodePudding user response:

You can make the validation in full_clean method of your model:

class GoForAWalk(models.Model):
    date = models.DateTimeField()
    location = models.CharField()

    owner = models.ForeignKey(Owner)
    dog = models.ForeignKey(Dog)

    def full_clean(self, **kwargs):
        super().full_clean(**kwargs)
    
        if self.dog.owner != self.owner:
            raise ValidationError(...)

Some information about full_clean: https://docs.djangoproject.com/fr/4.1/ref/models/instances/#django.db.models.Model.full_clean

With last Django version it is probably possible to make something with new Model Constraint: https://docs.djangoproject.com/fr/4.1/ref/models/instances/#validating-objects

  • Related