Django Unique Together约束报错问题求助
Hey there, let's break down why your test is failing and how to fix it. From what you've shared, the issue is that your Game model is enforcing a uniqueness constraint that's too broad—it's blocking different players from having games with the same text, which your test expects should be allowed.
Common Culprits to Check
First, let's look at two likely places where the problem is happening:
1. Overly Restrictive unique_together Constraint
If your Game model's Meta class has a unique_together setting that only includes text, that's the root cause. For example:
class Game(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) text = models.CharField(max_length=200) class Meta: # This is wrong—it makes text globally unique across all players unique_together = ['text']
This would prevent any two Game instances (even for different players) from having the same text. To fix it, update the constraint to include both player and text, so uniqueness is enforced per-player:
class Meta: unique_together = ['player', 'text']
2. Custom Clean Method with Incorrect Validation
If you added a custom clean() method to the Game model that checks for existing text without filtering by player, that's another common issue. For example:
def clean(self): # Wrong: checks all Games in the database for the same text if Game.objects.filter(text=self.text).exists(): raise ValidationError("This text is already in use")
Modify the filter to include the current player, so it only checks for duplicates within that player's games:
def clean(self): # Correct: only checks the current player's existing games if Game.objects.filter(player=self.player, text=self.text).exists(): raise ValidationError("You already have a game with this text")
Next Steps After Fixing the Model
Once you update the model, don't forget to:
- Generate a new migration file:
python manage.py makemigrations - Apply the migration to your database:
python manage.py migrate - Re-run your test suite—your
test_saves_same_game_with_different_playersshould now pass!
This aligns perfectly with the TDD approach Harry teaches: writing a failing test first, then adjusting your code to meet the test's expectations.
内容的提问来源于stack exchange,提问作者Diego-MX

