Skip to main content
 首页 » 编程设计

python之Django 变量不符合预期

2024年10月01日7qlqwjy

我有以下代码:

{% for x in fixtures %} 
    {% if currentSelectedTeam1Name == "Swansea" %} 
        <tr> 
            <td colspan="6"> 
                {{x.straightredfixturelive.home_team}} | {{currentSelectedTeam1Name}} 
            </td> 
        </tr> 
    {% endif %} 
{% endfor %} 

当我将团队硬编码为“斯旺西”时,它会工作并产生以下结果:

Swansea | Swansea 
Arsenal | Swansea 
Bournemouth | Swansea 

然而,我真正想要的是:

{% if currentSelectedTeam1Name == x.straightredfixturelive.home_team %} 

但这没有产生任何结果,这是我期望看到的结果:

Swansea | Swansea 

所以 x.straightredfixturelive.home_team 似乎包含“Swansea”但不匹配。我什至尝试过:

{% if x.straightredfixturelive.home_team == "Swansea" %} 

这也没有产生任何结果。因此,即使认为它在网页上显示为“斯旺西”,它似乎也不匹配。可能是数据类型问题?

模型信息:

class StraightredFixtureLive(models.Model): 
    fixtureid = models.OneToOneField( 
        StraightredFixture, 
        on_delete=models.CASCADE, 
        primary_key=True, 
    ) 
    home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures_live') 
    away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures_live') 
    fixturedate = models.DateTimeField(null=True) 
    fixturestatus = models.CharField(max_length=24,null=True) 
    fixturematchday = models.ForeignKey('straightred.StraightredFixtureMatchday', db_column='fixturematchday') 
    spectators = models.IntegerField(null=True) 
    hometeamscore = models.IntegerField(null=True) 
    awayteamscore = models.IntegerField(null=True) 
    homegoaldetails = models.TextField(null=True) 
    awaygoaldetails = models.TextField(null=True) 
    hometeamyellowcarddetails = models.TextField(null=True) 
    awayteamyellowcarddetails = models.TextField(null=True) 
    hometeamredcarddetails = models.TextField(null=True) 
    awayteamredcarddetails = models.TextField(null=True) 

请您参考如下方法:

您的问题是您将模型实例与字符串进行比较,因此它们永远不相等。

根据您的模型,您可能需要这样的东西:

{% if currentSelectedTeam1Name == x.straightredfixturelive.home_team.name %}