How to specify uniqueness in a relationship in Django

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.

+4
source share
3 answers

EDIT: Updated answer based on comments by @JoshSmeaton and @MSaavedra

Using the Django syncdb hook , you can run ALTER TABLE statements directly in the database. Django will raise an IntegrityError if a single constraint is violated, although this constraint has not been defined by django.

Then, adding a constraint on validate_unique subsequently reduce developer confusion and safely provide a constraint in Django.

+2
source

I think you should take a look at validate_unique

fooobar.com/questions/138554 / ...

Django Docs

+2
source

Source: https://habr.com/ru/post/1444642/


All Articles