Django 2.0.2 ValueError问题求助:models.py代码异常排查
Hey there, let's dig into that ValueError you're hitting with Django 2.0.2 and get it fixed up step by step.
核心问题分析
From the code snippet you shared, there are a few clear issues that are triggering that ValueError (or related definition errors):
Wrong order of model method and fields
In yourGameScoreclass, the__str__method is defined before thefirst_teamandsecond_teamfields. Python parses classes top-to-bottom, so when it tries to processself.first_teaminside__str__, that field hasn't been created yet—this will immediately throw an error.Incomplete field definition
Your code cuts off atsecond_team = models.F...—this is clearly an unfinishedForeignKeyfield definition. If your actual code leaves this field incomplete (missing parameters, unclosed syntax), Django will definitely throw a ValueError.Potential related_name conflict
You setrelated_name='first_team'for thefirst_teamfield. If you use the same related_name forsecond_team, Django will error out—related names for the same target model must be unique, which is a common trigger for ValueError.
Fixed Complete Code
Here's the corrected models.py code that resolves all these issues:
class Team(models.Model): name = models.CharField(max_length=256, unique=True) details = models.TextField() def __str__(self): return self.name class GameScore(models.Model): # Define all fields FIRST, then methods first_team = models.ForeignKey(Team, related_name='first_team_games', null=True, on_delete=models.PROTECT) second_team = models.ForeignKey(Team, related_name='second_team_games', null=True, on_delete=models.PROTECT) first_team_score = models.IntegerField() # Added the missing score fields your __str__ references second_team_score = models.IntegerField() def __str__(self): # Add null checks to avoid errors when fields are empty if self.first_team and self.second_team: return '{} {} - {} {}'.format(self.first_team.name, self.first_team_score, self.second_team_score, self.second_team.name) return 'Uncompleted Game Score'
Key Fixes Explained
- Reorder definitions: Move all field definitions above the
__str__method, so the fields exist when the method tries to access them. - Complete field setup: Fully define the
second_teamForeignKey, and add the missing score fields that your original__str__method references (these were missing in your code snippet, which would have caused another error). - Avoid related_name clashes: Use unique related names (
first_team_gamesandsecond_team_games) for each ForeignKey. This lets you easily query things liketeam.first_team_games.all()to get all games where the team was the first competitor. - Null-safe string representation: Add checks for
first_teamandsecond_teambeing null (since you setnull=True), preventing AttributeErrors when those fields are empty.
内容的提问来源于stack exchange,提问作者AbdullahMQ

