I'm trying to represent some movie ratings data in Django. Here is a simplified version of my models that illustrates my problem:
class RatingSystem(models.Model):
"""This denotes a rating authority and territory in which they operate"""
name = models.CharField(max_length=16)
territory = models.CharField(max_length=32)
class Rating(models.Model):
"""This represents a rating designation used by a rating system."""
code = models.CharField(max_length=16)
description = models.TextField()
system = models.ForeignKey(RatingSystem)
class FilmRating(models.Model):
"""This is a rating for a film and the reason why it received the rating.
Each film can have many ratings, but only one per rating system.
"""
rating = models.ForeignKey(Rating)
film = models.ForeignKey('Film')
reason = models.TextField()
class Film(models.Model):
"""Data for a film."""
title = models.CharField(max_length=64)
synopsis = models.TextField()
ratings = models.ManyToManyField(Rating, through=FilmRating)
As the comments indicate, each Film can have multiple ratings, but only one rating per rating system. For instance, a film cannot be rated both 'R' and 'PG' by the MPAA. However, it can be rated 'R' by the MPAA and '15' by the BBFC.
I'm struggling to formalize this constraint in Django. I'd like to do:
unique_together = ('film', 'rating__system')
in FilmRating
but following a relationship like that doesn't seem to be allowed. If I were using pure SQL, I would make code
and system
a composite primary key in Rating
, then make a unique constraint on system
, and film
in FilmRatings
. Unfortunately, Django does not support composite keys. I've considered overriding the save()
method of FilmRating
, but I'd prefer to have the constraint at the database level if possible.
Anyone have any idea how to do this? Restructuring the tables would be fine too if it would help.