0

class Player(models.Model):

name = models.CharField(max_length = 256)

number = models.IntegerField()

age = models.IntegerField()

is_captain = models.BooleanField(default = False)

class Injuries(models.Model):

player = models.ForeignKey(Player, Player.name)

team = models.ForeignKey(Team)
  • the error is: teams.Injuries.player: (fields.E312) The to_field '' doesn't exist on the related model 'teams.Player'. – zahir 9 Jan 05 '20 at 13:55

1 Answers1

0

Below are my suggestions, as per my capability.

As per the documentation,

A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option.

See the reference here. So the first positional argument is the class which is related by Foreign Key and the second position argument is on_delete. You should define it as models.CASCADE or as appropriate for your app. Thus in this case the second positional argument is "Player.name". I think you have to first replace it with models.CASCADE.

Thus change the code from what is below

class Injuries(models.Model):

    player = models.ForeignKey(Player, Player.name)
    team = models.ForeignKey(Team)

to the one below

class Injuries(models.Model):

    player = models.ForeignKey(Player, on_delete=models.CASCADE)
    team = models.ForeignKey(Team)

The foreign key is set to the primary key of the related model. In this case (since you have not defined it), it will be player_id that is automatically assigned by django. If you want it to force it to use the "name" column from the Player model, then you have to set "unique=True" in the name field of the Player model. Also notice the use of to_field='name' option.

In such a case the changed code will be as below.

class Player(models.Model):

    name = models.CharField(max_length = 256, unique=True)
    number = models.IntegerField()
    age = models.IntegerField()
    is_captain = models.BooleanField(default = False)

class Injuries(models.Model):

    player = models.ForeignKey(Player, to_field='name', on_delete=models.CASCADE)
    team = models.ForeignKey(Team)

Hopefully it will work. If there is still an error, please let me know.

Amit
  • 2,018
  • 1
  • 8
  • 12
  • @zahir9 I think you will have to follow a similar approach to the team field in the Injuries model class. on_delete= .. have to be provided and to_field if needed. I am sorry, I did not pay attention to the team field. I was focussed on player field of the Injuries model since that was the source of error. – Amit Jan 05 '20 at 15:03