2012-02-01 66 views
0

我有一個函數,如果我從django shell運行,它會成功填充我的數據庫。將值傳遞給自定義函數? django noob

我有三個類。

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() 

[編輯] furthur精心製作的,這裏是我的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 %} 

謝謝。

//鼠標

+2

這是什麼沒有做?告訴我們你是怎麼稱呼它的。 – Nix 2012-02-01 15:25:24

+0

添加了我的admin.py ..此刻,當我點擊按鈕生成裝置時,它將從團隊表中取得所有團隊。我只想把聯賽同伴帶到特定的聯賽。在django API中,它應該是'p = League.objects.get(id =?)'..其中id應該是動態的,按鈕應該設置它。然後'p.team_set.all()'..我想讓我的按鈕通過團隊ID值,然後我會適應我的功能相應..而不是做Team.objects.all().. – debuggerpk 2012-02-01 15:38:29

+0

您需要將其簡化爲基本代碼。這是相當數量的代碼供人們完成。 – Marcin 2012-02-01 17:24:14

回答

0

我的建議(盡我所能去了解你正在嘗試做的之後),使您的錨使用你的團隊的id的GET參數。

{% 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) 

這就是我可以根據你粘貼的代碼做的最好的。我強烈建議你將其中的一部分重寫爲更具可讀性。

相關問題