尝试使用ForeignKey时,UNIQUE约束失败

时间:2018-12-19 00:29:23

标签: django django-models

我有以下模型。py:

from django.db import models


class Restaurant(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)

    def __str__(self):
       return  self.name

class MenuSection(models.Model):
    restaurant = models.ForeignKey(
        Restaurant,
        on_delete=models.CASCADE,
        )
    food_type = models.CharField(max_length=50)
    def __str__(self):
       return self.food_type + " - " + self.restaurant.name


class MenuItem(models.Model):
    MenuSection = models.ForeignKey(
       MenuSection,
       on_delete=models.CASCADE,
        )
    food_item = models.CharField(max_length=50)
    def __str__(self):
       return self.food_item + " - " + self.restaurant.name

当我尝试迁移这些更改时,出现错误:“
no such column: core_menuitem.id”在命令行上,当我尝试访问/ admin时说:
no such column: core_menuitem.id”。有人知道这个问题是什么吗?预先感谢

1 个答案:

答案 0 :(得分:0)

请在MenyItem中重命名您的MenuSection字段,因为它与Foreign key类相同,此外,在CamelCase中为字段命名是不好的做法,并用下划线命名,如下所示:

class MenuItem(models.Model):
    menu_section = models.ForeignKey( # <- This field name
       MenuSection,
       on_delete=models.CASCADE,
    )
    food_item = models.CharField(max_length=50)

并尝试通过以下方式运行迁移:

python manage.py makemigrations
python manage.py migrate