Home > OS >  constrains on django model with ForeignKey
constrains on django model with ForeignKey

Time:02-08

Suppose we have this django models:

from django.db import models

# Create your models here.
class Artist(models.Model):
    name = models.CharField(max_length=10)

class Album(models.Model):
    name = models.CharField(max_length=10)
    date = models.DateField()
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)

So I can write:

artist_one = models.Artist.objects.create(name='Santana')
album_one = models.Album.objects.create(name='Abraxas', date = datetime.date.today(), artist=artist_one)
album_two = models.Album.objects.create(name='Supernatural', date = datetime.date.today(), artist=artist_one)

How can I add a constrain to the Album class as to say an artist cannot publish two albums the same year?

CodePudding user response:

Use validators on model

from django.core.exceptions import ValidationError
def validate_atrist_album(value):
    #logic to check if artist has album from same year here
    if not user_can_publish:
        raise ValidationError('Artist can't publish')



class Album(models.Model):
    name = models.CharField(max_length=10)
    date = models.DateField()
    artist = models.ForeignKey(
        Artist, 
        on_delete=models.CASCADE,
        validators=[
            validate_artist_album,
        ],
    )   

CodePudding user response:

You could override the model's save method like this.

    def save(self, *args, **kwargs):
        year = self.date.year
        albums_of_year = Album.objects.filter(artist=self.artist, date__year=year)
        if albums_of_year:
            # you can raise your error here
        else:
            super(Album, self).save(*args, **kwargs)
  •  Tags:  
  • Related