I have a model in Django which the pk
is not an integer and it has a field which is a manytomany
. This manytomany
references the model itself.
When I ran makemigration
I didn't realize, but it did not create the fields in the intermediate table as char(N)
. In fact, it create as an integer
.
# models.py
class Inventory(models.Model):
sample_id = models.CharField(max_length=50, primary_key=True)
parent_id = models.ManyToManyField("self")
This throws errors whenever I try to add objects to my parent model
>>> p = Inventory.objects.get(sample_id='sample01')
>>> child = Inventory.objects.get(sample_id='sample02')
>>> p.parent_id.add(child)
I get the error
psycopg2.DataError: invalid input syntax for integer: "sample02"
LINE 1: ...HERE ("inventory_parent_id"."to_inventory_id" IN ('sample...
I saw the fields in the intermediate table, inventory_parent_id
, created by Django and their types are not correct.
Columns (3)
|--id (integer)
|--from_inventory_id (integer)
|--to_inventory_id (integer)
My questions are: Is it bad if I change the types manually? Will it break the migrations? Or did I have to do something so Django can catch this misleading type?
Try to re-create migrations (unapply migrations by using ./manage.py migrate YOURAPP PREVIOUS_MIGRATION_NUMBER
or ./manage.py migrate YOURAPP zero
if it's initial migration), remove migration file (don't forget about .pyc
file) and generate it again.
If that doesn't help, you can try to create custom through table with proper migration fields and then recreate that migration.