Hi i'm trying to combine Django backend and postgresql database together.
Here is my database tables:
My models.py in Django
from django.db import models
# Create your models here.
class Categories(models.Model):
id = models.IntegerField(primary_key=True)
name = models.TextField(null=True, unique=True)
class Meta:
db_table = 'categories'
def __str__(self):
return self.name
class Website(models.Model):
id = models.IntegerField(primary_key=True)
site = models.TextField(null=True, unique=True)
class Meta:
db_table= 'website'
def __str__(self):
return self.site
class Discount(models.Model):
id = models.IntegerField(primary_key=True)
product_name = models.TextField()
product_price = models.TextField()
product_old_price = models.TextField()
product_link = models.TextField()
category_name = models.ForeignKey(Categories, on_delete=models.CASCADE, null=True, to_field='name')
product_site = models.ForeignKey(Website, on_delete=models.CASCADE, null=True, to_field='site')
product_image = models.TextField()
class Meta:
db_table = 'discount'
def __str__(self):
return self.product_name
I managed to link Django and postgresql together following tutorials but when i try to migrate the database for the first time it come with this error :
column discount.category_name_id does not exist LINE 1: ..."."product_old_price", "discount"."product_link", "discount"... ^ HINT: Perhaps you meant to reference the column "discount.category_name".
i though i linked my foreign key from discount.category_name to categories.name with to_field='name' in the ForeignKeyField but somehow it used the discount.category_name_id ? i don't know where the category_name_id is, it's not in my tables
Any help would be appreciate!
I managed to fixed it by adding
db_column='category_name'
to the ForeignKey field
It seems that i need to specific what column that actually is a Foreign key in my Postgresql tables to the ORM
category_name = models.ForeignKey(Categories, on_delete=models.CASCADE, null=True, to_field='name', db_column='category_name')
product_site = models.ForeignKey(Website, on_delete=models.CASCADE, null=True, to_field='site', db_column='product_site')