2012-01-21 2 views
1

해당 CompetitionEntry 모델이있는 경쟁 모델이 있습니다. 관리자보기에서 각 경기의 항목 수를 표시하고 싶습니다. 오른쪽관리자 목록보기에 외래 키 개체 수 표시

class Competition(models.Model): 

    def __unicode__(self): 
     return self.competition_name 

    competition_name = models.CharField(max_length=100) 
    competition_text = models.TextField() 
    active = models.BooleanField('Is this competition active?', blank=True) 
    date_posted = models.DateTimeField(auto_now_add=True) 

class CompetitionEntry(models.Model): 

    def __unicode__(self): 
     return self.competition.competition_name 

    competition = models.ForeignKey(Competition) 
    user = models.ForeignKey(User) 
    date_entered = models.DateTimeField(auto_now_add=True) 
    is_winner = models.BooleanField('Is this entry the winner?', blank=True) 

내 장고 기술을 약간 녹슨하지만, 관리자에게이 문제를 추가 할 수있는 매우 간단한 방법이 있어야한다 :

여기에 모델 정의입니까? 어떤 포인터? CompetitionEntry 내부에서 관계가 정의 되었기 때문에 Competition 클래스가 CompetitionEntry 클래스와 '대화 할 수있는 방법'을 잘 이해할 수 없지만 CompetitionEntry 클래스 내에 항목을 표시하려고합니다.

답변

1

ModelAdmin의 파이썬 함수를 fieldsets 또는 list_displayreadonly_fields 속성에 추가하여 참조 할 수 있습니다.

외래 키가 가리키는 각 클래스에 동적으로 추가 된 역방향 관련 관리자를 통해 역방향 관계를 '말하기'할 수 있습니다. 기본값은 lowercasemodelname_set이며 기본값은 objects 관리자와 똑같습니다.

class MyAdmin(admin.ModelAdmin): 
    list_display = ('_competition_count',) 
    readonly_fields = ('_competition_count',) 

    fieldsets = (
     (None, {'fields': (
      '_competition_count', 
     )}) 
    ) 

    def _competition_count(self, obj): 
     return obj.competitionentry_set.count() 
    _competition_count.short_description = "Competition Count" 
+0

환상적입니다. 이것이 내가 필요한 것입니다. 고맙습니다! –