在django中将方法从父类继承到多个子类的最佳方法

时间:2017-06-06 16:58:34

标签: python django inheritance

我有多个子类,它们使用非常相似的方法,我想传递不同的参数。例如,我正在使用父子类SportsSentiment,其中包含一个返回单个联盟(NBA,NFL,MLB等)的所有行的函数。

这是父类:

from django.db import models
from sports_sentiment.main.models import SentimentPoint

class SportsSentimentMixin(models.Model):
    test = "abc"

    # I want my subclasses to inherit this method!
    def get_league_sentimental_points(self, league):
        return SentimentPoint.objects.all().filter(league=league)


    class Meta:
        abstract = True

子类的一个例子:

from sports_sentiment.custom_mixins import SportsSentimentMixin

class NBASportsSentimentView(TemplateView, SportsSentimentMixin):
    template_name = 'NBA/sports_sentiment.html'

    # This doesn't work, but I'm trying to get the the 
    # the function get_league_sentimental_points from the parent
    # class
    nba_data = self.get_league_sentimental_points("NBA")

1 个答案:

答案 0 :(得分:0)

我认为你会有点倒退。首先,你的mixin不需要是一个模型。为什么不把它作为基于联盟查询情绪点的基本视图。然后,您可以继承该视图并覆盖template_nameleague

from django.views.generic import TemplateView
from sports_sentiment.main.models import SentimentPoint


class SportsSentimentView(TemplateView):
    template_name = 'ABC/sports_sentiment.html'
    league = 'ABC'

    def get_context_data(self, **kwargs):
        # This method builds a dictionary of variables that will be passed
        # to the template for rendering
        context = super(SportsSentimentView, self).get_context_data(**kwargs)
        context['points'] = SentimentPoint.objects.filter(league=self.league)
        return context


class NBASportsSentimentView(SportsSentimentView):
    template_name = 'NBA/sports_sentiment.html'
    league = 'NBA'

# Adding more leagues is now super simple!
class NHLSportsSentimentView(SportsSentimentView):
    template_name = 'NHL/sports_sentiment.html'
    league = 'NHL'