I am trying to present some movie rating 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 show, each film can have several ratings, but only one rating for the rating system. For example, a film cannot be rated as โRโ and โPGโ by MPAA. However, it can be rated โRโ MPAA and โ15โ BBFC.
I am trying to formalize this restriction in Django. I would like to:
unique_together = ('film', 'rating__system')
at FilmRating , but after that kind of relationship doesn't seem to be allowed. If I used pure SQL, I would make code and system composite primary key in Rating , then create a unique constraint on the system and film in FilmRatings . Unfortunately, Django does not support composite keys. I considered overriding the save() FilmRating , but I would prefer to have a database-level restriction if possible.
Does anyone know how to do this? Restructuring tables would also be nice if that helped.
source share