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

2024-06-16 14:11:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个子类,它们使用非常相似的方法来传递不同的参数。例如,我使用的父类sportsmotation包含一个函数,该函数返回单个联盟(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")

Tags: thefromimportgetmodels子类pointsclass
1条回答
网友
1楼 · 发布于 2024-06-16 14:11:56

我觉得你有点倒退了。首先,你的混音不需要是一个模型。为什么不让它成为一个基本的观点,根据联赛的情绪点查询。然后您就可以从该视图继承并重写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'

相关问题 更多 >