Python Django how to share a foreign key?
In models.py, when I define a unique key on a model and then call it by another model under different variable names, it will not add those columns to the Sqlite table. Please, how to solve?
In my case, I want to define unique locations (location_id), then define movements between those locations (location_from, location_to).
This is my code:
# models.py
class Locations(models.Model):
location_id = models.CharField(max_length = 10, unique=true)
class Movements(models.Model):
blabla = models.CharField(max_length = 10, unique=true)
location_id = models.ForeignKey(Locations, on_delete=models.CASCADE, related_name='location_from')
location_id = models.ForeignKey(Locations, on_delete=models.CASCADE, related_name='location_to')
After makemigrations and migrate, the table Movements in db.sqlite3 does not contain the fields location_from and location_to.
What happened? My language is clearly wrong. Please, how to make it right?
I just fixed the possible errors in your code.
# models.py
class Locations(models.Model):
location_id = models.CharField(max_length = 10, unique=true)
class Movements(models.Model):
blabla = models.CharField(max_length = 10, unique=True)
location_from = models.ForeignKey(Locations, on_delete=models.CASCADE, related_name='location_from')
location_to = models.ForeignKey(Locations, on_delete=models.CASCADE, related_name='location_to')