【问题标题】:Django model method returning correct response when called from shell but not when called from templateDjango 模型方法在从 shell 调用时返回正确响应,但从模板调用时不返回正确响应
【发布时间】:2020-04-02 22:29:15
【问题描述】:

models.py

class player(models.Model):
    name = models.CharField(max_length = 100)
    rounds_played = models.IntegerField()
    rounds_missed = models.IntegerField()
    date_joined = models.DateTimeField(default = timezone.now)
    total_points = models.IntegerField()
    bio = models.TextField()
    user_ID = models.CharField(max_length = 10)
    user_m = models.ForeignKey(User, on_delete=models.CASCADE)
    is_active = models.BooleanField(),
    def rounds_record(self):
        return int(100 * self.rounds_played / (self.rounds_played + self.rounds_missed))
    def player_status(self):
        if self.is_active:
            return "Yes"
        return "No"
    def average_points(self):
        return int(self.total_points / self.rounds_played)
    def __str__(self):
        return self.name

模板sn-p

{% for player in players %}
<div class = "grid-item">
        {{player.player_status}}
</div>
{% endfor %}

我正在开发一个数据库网络应用程序(用于学习 django),其中团队中的球员及其统计数据被跟踪并存储在 psql 数据库中。当从 manage.py shell 调用 player_status 方法时,它会返回正确的响应,例如,对于每个用户,“是”、“否”。

但是,当从模板调用该方法时,该方法返回“yes”、“yes”。经过一些故障排除后,我发现它确实为每个响应返回了 true。我能做些什么来解决这个问题。

编辑:我应该指定我目前有 2 个测试用户,一个存储 True,另一个存储 False 在 is_active BooleanField

【问题讨论】:

    标签: python django shell django-models django-templates


    【解决方案1】:

    由于您没有发布视图代码,因此很难判断一切是否正确实现。

    我还猜想您在模板中显示了玩家名称,并且您看到它返回的是您实际拥有的 2 个玩家,而不是同一玩家的两倍(这可能解释了为什么您会看到两次 Yes)。

    除此之外,它看起来还不错,应该可以工作。

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多