2011-03-21 4 views
2

내가 3 개 모델 클래스가 : 팀이있는 경우 즉, (나는 일치의 목록을 할 수있는 팀이 수상했다 얼마나, 그들이 바로 지금과 같이 모델을 사용뒤로 외래 키에 의해 필터 전달

class Team(models.Model): 
    name = models.CharField(max_length=100, default="", blank=True, null=True) 
    number = models.IntegerField() 

class Position(models.Model): 
    match = models.ForeignKey('Match') 
    color = models.CharField(max_length=5) 
    number = models.IntegerField() 

    team = models.ForeignKey('Team') 

class Match(models.Model): 
    type = models.CharField(max_length=3) 
    number = models.IntegerField() 

    red_score = models.IntegerField(default=0) 
    blue_score = models.IntegerField(default=0) 

    match_events = models.TextField(max_length=1000) 

을 빨간색 위치에 속하며 일치 항목에 red_score> blue_score가 있으면 목록에 추가하십시오.

죄송합니다. 특정 질문이있을 경우 명확히하기 위해 노력할 수 있습니다.

감사합니다. 이 작업을 수행하는

답변

2

간단한 방법 :

Match.objects.filter(position__color='red', red_score__gt=F('blue_score')) 

당신은 외래 키 관련 모델 이름에서 아포스트로피를 제거, 바닥에 Position 모델을 이동할 수 있습니다. team는 실제 팀과 단일 match입니다 경우 :이 경우

class Team(models.Model): 
    name = models.CharField(max_length=100, default="", blank=True, null=True) 
    number = models.IntegerField() 


class Match(models.Model): 
    type = models.CharField(max_length=3) 
    number = models.IntegerField() 
    red_score = models.IntegerField(default=0) 
    blue_score = models.IntegerField(default=0) 
    match_events = models.TextField(max_length=1000) 
    teams = models.ManyToManyField(Team, through='Position', 
            related_name='matches') 


class Position(models.Model): 
    match = models.ForeignKey(Match) 
    color = models.CharField(max_length=5) 
    number = models.IntegerField() 
    team = models.ForeignKey(Team) 

, 당신은 몇 가지 더 많은 옵션 데이터 액세스, 예를 단순화하기 위해 얻을 것이다 :

이 ManyToMany 관계를 사용하는 아주 좋은 예는 잘 일치하는 코드의 앞부분에서 선택하면 유효합니다.

team.matches.filter(red_score__gt=F('blue_score')) # all won matches of this team 

match.teams.all() # teams involved in this match 
+0

고마워요! 새로운 무언가를 매일 배우십시오 :-) – Zooey

관련 문제