我试图验证我的篮球联赛经理的数据,我得到了大部分简单的数据,但我不知道如何处理他们中的几个。< / p>
我有Game
模型和PlayerBoxscore
模型与Game
ForeginKey
相关联(该游戏中的每个玩家都有PlayerBoxscore
并且具有所有统计数据,即is_starter
和min
。
我在Django Admin via中更改PlayerBoxscore
时添加了所有Game
个。 inlines
,按Team
分组。
如何确保PlayerBoxscore
中只有Team
个is_starter
True
设置为PlayerBoxscore
?
类似的 - 如何确保所有Team
s(x
)中的分钟总和相等Game
。
我不知道在哪里进行验证;它涵盖了与PlayerBoxscore
关联的所有对象,因此我无法将其放在clean
class AwayPlayerBoxscoresInline(admin.TabularInline):
model = PlayerBoxscore
verbose_name_plural = 'Away players'
exclude = ['team']
readonly_fields = ['player']
extra = 0
max_num = 0
can_delete = False
def get_queryset(self, request):
# Returns only players from away team
qs = super(AwayPlayerBoxscoresInline, self).get_queryset(request)
if request.obj is not None:
return qs.filter(player__team=request.obj.away_team)
else:
return qs
class HomePlayerBoxscoresInline(admin.TabularInline):
model = PlayerBoxscore
verbose_name_plural = 'Home players'
exclude = ['team']
readonly_fields = ['player']
extra = 0
max_num = 0
can_delete = False
def get_queryset(self, request):
# Returns only players from home team
qs = super(HomePlayerBoxscoresInline, self).get_queryset(request)
if request.obj is not None:
return qs.filter(player__team=request.obj.home_team)
else:
return qs
@admin.register(Game)
class GameAdmin(admin.ModelAdmin):
view_on_site = True
list_display = ('pk', 'away_team', 'home_team', 'score', 'winner', 'date', 'overtime')
list_filter = ['away_team', 'home_team']
fieldsets = [
('Game info', {'fields': ['away_team', 'home_team', 'date']})
]
@staticmethod
def score(obj):
return '{away} - {home}'.format(away=obj.final_score['away_team'], home=obj.final_score['home_team'])
def get_form(self, request, obj=None, **kwargs):
request.obj = obj
return super(GameAdmin, self).get_form(request, obj, **kwargs)
def change_view(self, request, object_id, form_url='', extra_context=None):
if self.get_object(request, object_id).date <= date.today():
PeriodScoreInline.extra = 0
self.inlines = [PeriodScoreInline, AwayPlayerBoxscoresInline, HomePlayerBoxscoresInline]
else:
self.inlines = []
return super(GameAdmin, self).change_view(request, object_id, form_url, extra_context)
方法中,或在保存所有内容时触发它,因为我想阻止它在没有满足这些条件的情况下得救。
提前致谢
admin.py:
{{1}}
答案 0 :(得分:0)
您可以为inlineadmin类定义自定义formset。该formset上的一个干净的方法将是这个逻辑的适当位置。