我有一个函数,如果我从django shell运行,它会成功填充我的数据库。
我有三节课。
Class League(models.Model):
LeagueName = models.CharField()
#class League explained below
Class Fixture(models.Model):
League = models.ForeignKey(League)
home_team = models.ForeginKey(Team)
away_team = models.ForeginKey(Team)
Class Teams(models.Model):
League = models.ForeignKey(League)
我希望该功能能够仅针对一个联赛计算灯具表。这就是我现在正在做的事情。目前它还没有做到。怎么样?
class League(models.Model):
LeagueName = models.CharField(max_length=200)
FixturesGenerated = models.BooleanField(default=False)
def __unicode__(self):
return self.LeagueName
def CreateFixtures(self, print_only=True):
if self.FixturesGenerated==True:
return
from dateutil import rrule
from dateutil.relativedelta import *
from League.models import Team, Fixture
import itertools
import datetime
import random
"""
Instead of your array I will use actual objects from the Teams model
"""
teams = Team.objects.all()
fixcombos = list(itertools.combinations(teams,2))
random.shuffle(fixcombos)
nofixtures = len(fixcombos)
datestart = datetime.date.today()
dateend = datestart + datetime.timedelta(days=125)
#calculate possible fixture dates,
fixdays = list(rrule.rrule(rrule.DAILY, byweekday=(rrule.SA,rrule.SU), dtstart=datestart, until=dateend))
nofmatchdays = len(fixdays)
# perday = perday matches, and then moved it into array for for loop of dates available.
perday = nofixtures/nofmatchdays +1
perday = range(0,perday)
#for loop to extend the fixture days array to repeat dates.
for x in perday:
fixdays = fixdays + fixdays
fixarray = range(0, nofixtures)
# for loop for printing the possible functions
# this for loop number will give the database entry id number of a particular name. we still have to do some manipulation.
result = ''
for y in fixarray:
printline = 'Date: ' + str(fixdays[y]) + ': Teams Involved: ' + str(fixcombos[y])
result += printline
# now the print array functionality needs to be replaced with p.save() functionality in the final program.
"""
Code to actually save the fixture if print_only is not True
"""
if not print_only:
f = Fixture()
f.league = self
f.fixture_date = fixdays[y]
f.team_one = fixcombos[y][0]
f.team_two = fixcombos[y][1]
f.save()
self.FixturesGenerated = True
self.save()
[编辑]为了进一步详细说明,这是我的admin.py
from League.models import League
from League.models import Team
from League.models import Fixture
from django.contrib import admin
from django.http import HttpResponseRedirect
class ButtonableModelAdmin(admin.ModelAdmin):
buttons=()
def change_view(self, request, object_id, extra_context={}):
extra_context['buttons']=self.buttons
return super(ButtonableModelAdmin, self).change_view(request, object_id, extra_context)
def button_view_dispatcher(self, request, object_id, command):
obj = self.model._default_manager.get(pk=object_id)
return getattr(self, command)(request, obj) \
or HttpResponseRedirect(request.META['HTTP_REFERER'])
def get_urls(self):
from django.conf.urls.defaults import patterns, url
from django.utils.functional import update_wrapper
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.module_name
return patterns('',
*(url(r'^(\d+)/(%s)/$' % but[0], wrap(self.button_view_dispatcher)) for but in self.buttons)
) + super(ButtonableModelAdmin, self).get_urls()
class TeamsInLeague(admin.StackedInline):
model = Team
extra = 1
class FixturesInLeague(admin.TabularInline):
model = Fixture
extra = 0
class LeagueAdmin(ButtonableModelAdmin):
fields = ['LeagueName', 'FixturesGenerated']
inlines = [TeamsInLeague, FixturesInLeague, ]
def gen_fixtures(self, request, obj):
obj.CreateFixtures(print_only=False)
gen_fixtures.short_description = 'Generate Fixtures'
gen_fixtures.url = "gen_fixtures"
buttons = [ (gen_fixtures.func_name, gen_fixtures.short_description) ]
admin.site.register(League,LeagueAdmin)
admin.site.register(Team)
admin.site.register(Fixture)
这里来自我的模板/../ change_form.html。
{% extends "admin/change_form.html" %}
{% block object-tools %}
{% if change %}{% if not is_popup %}
<ul class="object-tools">
{% for button in buttons %}
<li><a href="{{ button.0 }}/">{{ button.1 }}</a></li>
{% endfor %}
<li><a href="history/" class="historylink">History ala bala</a></li>
{% if has_absolute_url %}<li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">View on site</a></li>{% endif%}
</ul>
{% endif %}{% endif %}
{% endblock %}
三江源。
//小鼠
答案 0 :(得分:0)
我的建议(在尽力了解您要做的事情之后)是让您的主持人使用您的团队ID的获取参数。
{% for button in buttons %}
<li><a href="{{ button.0 }}?team_id={{team_id}}/">{{ button.1 }}</a></li>
{% endfor %}
然后在您的视图中,您可以从请求中提取团队ID并调用CreateFixtures。
team = request.get('team_id')
league.CreateFixtures(team, print_only=False)
根据您粘贴的代码,我能做的最好。我强烈建议你重做一些更具可读性。