Reputation: 39
I'm working on the Django section of CS50 around the 30min mark on the video with the modes 'ForeignKey' section.
When i run the make migration i get the error.
You are trying to add a non-nullable field 'agent' to product without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 2
if I set the default as a string value i get the error saying it was expecting an id.
If i set it as 1 then i get the following.
The row in table 'clutter_product' with primary key '1' has an invalid foreign key: clutter_product.agent_id contains a value '1' that does not have a corresponding value in clutter_supplier.id.
class Supplier(models.Model):
company = models.CharField(max_length=64)
contact = models.CharField(max_length=64)
email = models.CharField(max_length=128, blank = True)
def __str__(self):
return f"{self.id} {self.company} {self.contact} {self.email}"
class Product(models.Model):
name = models.CharField(max_length=64)
sku = models.CharField(max_length=64, blank = True)
unit_cost = models.IntegerField()
rrp = models.IntegerField()
average_fee = models.IntegerField()
shipping_fee = models.IntegerField()
agent = models.ForeignKey(Supplier, default=1, on_delete=models.CASCADE, related_name="suppliers")
Upvotes: 0
Views: 3232
Reputation: 51988
I would suggest to try these steps:
First, delete the migration file which is causing this problem.
Second change the model like this:
class Product(models.Model):
# rest of the fields
agent = models.ForeignKey(Supplier, null=True, default=None, on_delete=models.CASCADE, related_name="suppliers")
Third run makemigrations and migrate.
Fourth create a instance of supplier using supplier = Supplier.objects.create(company="ABC", contact="contact", email="[email protected]", pk=1)
Fifth(optional) Update the existing Product to haven a supplier-Product.objects.update(agent=supplier)
.
Sixth, if you want to constrain Products to be created with an agent, then remove null=True, default=None
from agent
field in Product
model. Then run makemigrations and migrate.
Upvotes: 4