1

I have a MySQL database object that stores concerts that a User plans to attend on a certain date. Since each concert entry needs to be associated with a User, I added a foreign key field for User as an attribute of the Concert model. Here is the complete model:

class Concert(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    concert_name = models.CharField(max_length = 120, blank = True, null = True)
    venue = models.CharField(max_length = 120, blank = True, null = True)
    city = models.CharField(max_length = 120, blank = True, null = True)
    state = models.CharField(max_length = 120, blank = True, null = True)
    country = models.CharField(max_length = 120, blank = True, null = True)
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)

When I try to make migrations to the DB, I get a message saying: You are trying to add a non-nullable field 'user' to concert with out a default; s essentially saying that the already populated rows need to have a value. I found this SO post which seemed to be addressing a similar issue, but the default value suggested in the solution is for a charfield and I don't think that would really apply in this situation. How should I go about setting the default value of the User object?

Community
  • 1
  • 1
loremIpsum1771
  • 2,497
  • 5
  • 40
  • 87

1 Answers1

3

You can use null=True:

user = models.ForeignKey(User, null=True)

Although if you look at your db actual model, you cannot see an actual Foreign Key, when you put models.ForeignKey(User) in your model you can see in your db a user_id with references, but the relation needed exists so you can make it's null=True as a default.

Idos
  • 15,053
  • 14
  • 60
  • 75
P3zhman
  • 243
  • 3
  • 12