Reputation: 2339
I am following a book tutorial for Django applications (keyword: TDD, link: here, author: Harry Percival), and I made small changes which now break my code.
def test_saves_same_game_with_different_players(self):
player1 = Player.objects.create(name="Player1")
player2 = Player.objects.create(name="Player2")
Game.objects.create(player=player1, text="score: other_player")
game2 = Game.objects.create(player=player2, text="score: other_player")
game2.full_clean() # Should not raise.
class Player(models.Model):
name = models.TextField(default="")
objects = models.Manager()
def __str__(self):
return self.name
class Game(models.Model):
player = models.ForeignKey(Player, default=None)
text = models.TextField(default="", unique=True)
objects = models.Manager()
def __str__(self):
return self.text
class Meta:
ordering = ("id",)
unique_together = ("player", "text")
...
game2 = Game.objects.create(player=player2, text="score: other_player")
...
IntegrityError: UNIQUE constraint failed: games_game.text
and also with sqlite
.
The error is with the unique_together
constraint when creating the second game with the same text. But this happens even when the players have different names, and even use the name as a string representation.
Would anyone know how to go about this? Thank you for your patience.
Cheers.
Upvotes: 0
Views: 428
Reputation: 1368
text = models.TextField(default="", unique=True)
This is where your code is falling because you make text as a unique field.
Upvotes: 1