장고에서 영화 등급 데이터를 표시하려고합니다. 코멘트는 표시로Django에서 관계의 독창성을 지정하는 방법
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)
, 각 필름은 여러 등급을 가질 수 있지만, 평가 시스템 당 하나 개의 평가 : 여기에 단순화 된 내 문제를 보여 내 모델의 버전입니다. 예를 들어 영화는 MPAA에서 'R'과 'PG'등급을받을 수 없습니다. 그러나 MPAA는 'R'등급을, BBFC는 '15'등급을 매길 수 있습니다.
장고에서이 제약 조건을 공식화하는 데 어려움을 겪고 있습니다. 내가 할 싶습니다
unique_together = ('film', 'rating__system')
FilmRating
에서하지만 그런 관계를 다음과 허용하지 않는 것 같습니다. 순수 SQL을 사용하는 경우 Rating
에 code
과 system
을 복합 기본 키로 만든 다음 system
및 film
을 FilmRatings
에 고유 제한을 적용합니다. 아쉽게도 Django는 복합 키를 지원하지 않습니다. FilmRating
의 save()
메서드를 재정의하는 것으로 생각했지만 가능하면 데이터베이스 수준의 제약 조건을 선호합니다.
누구나 어떻게해야할까요? 도움이된다면 테이블을 재구성하는 것도 괜찮을 것입니다.
db 제약 조건을 추가하는 것이 최종 방어로서 좋은 생각이지만, validate_unique 메소드를 사용하면 개발자가 장고에있을 수있는 오해를 해결할 수 있습니다. –
아마도'sql/ .sql' 파일 안에있는 alter table 문을 실행하는 것이 SQL을 처리하는 가장 좋은 방법이 될 것이므로 데이터베이스가 다시 생성되면 자동으로 실행될 것입니다.당신과 @ JoshSmeaton은 Django 내에서 유효성 검사를하는 것이 필요하고, 원시 SQL 제약을 마지막 방어선으로 남겨 두는 것이 옳다. –
@MSaavedra, 정말 유용합니다! 나는 sql 특정 syncdb 후크에 대해 몰랐다. – Arion