Django postgres 迁移模型列 discount.category_name_id 不存在

Django postgres migrate models column discount.category_name_id does not exist

您好,我正在尝试将 Django 后端和 postgresql 数据库结合在一起。

这是我的数据库表:

我在 Django 中的 models.py

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

我设法 link 按照教程将 Django 和 postgresql 结合在一起,但是当我第一次尝试迁移数据库时出现此错误:

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".

我虽然在 ForeignKeyField 中使用 link 将我的外键从 discount.category_name 编辑到 categories.name to_field='name' 但不知何故它使用了 discount.category_name_id ?我不知道 category_name_id 在哪里,它不在我的表格中

任何帮助将不胜感激!

以下字段未反映在数据库中,请检查您的数据库字段名称,如果没有,请创建一个虚拟迁移并为此编写脚本

    category_name = models.ForeignKey(Categories, on_delete=models.CASCADE, null=True, to_field='name')

我设法通过添加

修复了它

db_column='category_name'

到外键字段

看来我需要具体说明在我的 Postgresql 表中哪个列实际上是 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')