python-3.6django-1.11

i can't do makemigrations in django 1.11 (fields.E312)


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)

Solution

  • 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.